Interval Tree - Problem
Implement an interval tree data structure that efficiently finds all intervals that overlap with a given query interval.
An interval is represented as [start, end] where both start and end are integers. Two intervals [a, b] and [c, d] overlap if they have at least one point in common: max(a, c) ≤ min(b, d).
Your task is to implement an IntervalTree class with the following methods:
IntervalTree(intervals): Constructor that builds the tree from a list of intervalsquery(queryInterval): Returns all intervals that overlap with the given query interval
Input & Output
Example 1 — Basic Overlapping Intervals
$
Input:
intervals = [[1,3],[2,6],[8,10],[15,18]], queryInterval = [4,8]
›
Output:
[[2,6]]
💡 Note:
Only [2,6] overlaps with [4,8] because max(2,4)=4 ≤ min(6,8)=6. The intervals [1,3], [8,10], and [15,18] do not overlap with [4,8].
Example 2 — Multiple Overlaps
$
Input:
intervals = [[1,4],[2,3],[5,7]], queryInterval = [2,5]
›
Output:
[[1,4],[2,3],[5,7]]
💡 Note:
All three intervals overlap with [2,5]: [1,4] overlaps at [2,4], [2,3] is completely contained, and [5,7] overlaps at point 5.
Example 3 — No Overlaps
$
Input:
intervals = [[1,2],[3,4]], queryInterval = [5,6]
›
Output:
[]
💡 Note:
Neither [1,2] nor [3,4] overlaps with [5,6] since there are no common points between them.
Constraints
- 1 ≤ intervals.length ≤ 104
- intervals[i].length == 2
- queryInterval.length == 2
- -106 ≤ starti, endi, queryStart, queryEnd ≤ 106
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code