Remove Interval - Problem

A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form [a, b). A real number x is in the set if one of its intervals [a, b) contains x (i.e. a <= x < b).

You are given a sorted list of disjoint intervals intervals representing a set of real numbers as described above, where intervals[i] = [ai, bi] represents the interval [ai, bi).

You are also given another interval toBeRemoved. Return the set of real numbers with the interval toBeRemoved removed from intervals. In other words, return the set of real numbers such that every x in the set is in intervals but not in toBeRemoved.

Your answer should be a sorted list of disjoint intervals as described above.

Input & Output

Example 1 — Basic Interval Removal
$ Input: intervals = [[0,2],[3,4],[4,6]], toBeRemoved = [1,3]
Output: [[0,1],[3,4],[4,6]]
💡 Note: Interval [0,2] overlaps with [1,3], so we keep [0,1]. Intervals [3,4] and [4,6] don't overlap with [1,3], so they remain unchanged.
Example 2 — Complete Removal
$ Input: intervals = [[0,5]], toBeRemoved = [2,3]
Output: [[0,2],[3,5]]
💡 Note: The interval [0,5] contains [2,3], so we split it into two parts: [0,2] and [3,5], removing the middle section [2,3].
Example 3 — No Overlap
$ Input: intervals = [[0,1],[2,3],[4,5]], toBeRemoved = [6,7]
Output: [[0,1],[2,3],[4,5]]
💡 Note: No intervals overlap with [6,7], so all original intervals remain unchanged.

Constraints

  • 1 ≤ intervals.length ≤ 104
  • -109 ≤ ai < bi ≤ 109

Visualization

Tap to expand
Remove Interval - One-Pass Processing INPUT Number Line 0 1 2 3 4 5 6 [0,2) [3,4) [4,6) toBeRemoved: [1,3) intervals: [0,2] [3,4] [4,6] toBeRemoved: [1, 3] Remove red from blue ALGORITHM STEPS 1 Iterate intervals Process each [a,b) 2 Check overlap Compare with [1,3) 3 Handle cases Split/trim if needed 4 Add to result Keep valid parts Processing [0,2] with [1,3]: Before: [0,2) Overlap: [1,2) After: [0,1) OK - kept! [3,4], [4,6] no overlap - keep FINAL RESULT Result Number Line 0 1 2 3 4 5 6 [0,1) [3,4) [4,6) removed Output: [0,1] [3,4] [4,6] Interval Removed - OK [1,3) successfully excluded [0,2] split into [0,1] [3,4], [4,6] unchanged Time: O(n), Space: O(n) Key Insight: For each interval [a,b), compare with removal [start,end). Three cases: no overlap (keep as-is), partial overlap (trim the overlapping part), or split (removal is in middle). Process left-to-right in one pass. Add [a, start) if a is less than start, and [end, b) if end is less than b. TutorialsPoint - Remove Interval | One-Pass Interval Processing
Asked in
Google 25 Amazon 18 Microsoft 15
12.5K Views
Medium Frequency
~15 min Avg. Time
456 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