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 intervals
  • query(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
INPUT[1,3][2,6][8,10][15,18]Query [4,8]ALGORITHM1Build BST by start time2Augment with max endpoints3Query with pruning4Collect overlapping intervalsRESULT[[2,6]]Only [2,6] overlapswith query [4,8]Key Insight:Augmenting BST nodes with maximum endpoints enables O(log n) pruning of impossible subtreesTutorialsPoint - Interval Tree | Optimized Tree Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
28.5K Views
Medium-High Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen