Remove Interval - Problem
Imagine you're managing a calendar booking system where time slots are represented as intervals. You have a collection of non-overlapping time slots that are currently booked, and you need to cancel one specific booking that might overlap with multiple existing slots.
Given a sorted list of disjoint intervals intervals where each interval [a, b) represents a half-open interval (includes a but excludes b), and another interval toBeRemoved, return the resulting intervals after removing the specified interval.
Key Points:
- Intervals are half-open:
[a, b)includesabut excludesb - Input intervals are already sorted and non-overlapping
- The removal might split existing intervals or completely remove them
- Return the final set as sorted disjoint intervals
Input & Output
example_1.py โ Basic Removal
$
Input:
intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
โบ
Output:
[[0,1],[6,7]]
๐ก Note:
The removal interval [1,6) partially overlaps with [0,2) and [5,7). From [0,2), we keep [0,1). From [5,7), we keep [6,7). The interval [3,4) is completely contained in [1,6) so it's removed entirely.
example_2.py โ Complete Removal
$
Input:
intervals = [[0,5]], toBeRemoved = [2,3]
โบ
Output:
[[0,2],[3,5]]
๐ก Note:
The interval [0,5) is split by removing [2,3). This creates two new intervals: [0,2) and [3,5), both of which are outside the removed region.
example_3.py โ No Overlap
$
Input:
intervals = [[0,5]], toBeRemoved = [5,6]
โบ
Output:
[[0,5]]
๐ก Note:
Since intervals use half-open notation [a,b), the interval [0,5) ends at 5 (exclusive) and [5,6) starts at 5 (inclusive). There's no overlap, so the original interval is preserved.
Constraints
- 1 โค intervals.length โค 104
- intervals[i].length == 2
- 0 โค ai < bi โค 109
- intervals is sorted by ai in ascending order
- toBeRemoved.length == 2
- 0 โค toBeRemoved[0] < toBeRemoved[1] โค 109
Visualization
Tap to expand
Understanding the Visualization
1
Identify Affected Bookings
Scan through existing reservations to find those that overlap with the cancellation
2
Handle Partial Overlaps
For bookings that partially overlap, split them to preserve non-cancelled portions
3
Remove Complete Overlaps
Entirely remove bookings that fall completely within the cancellation
4
Maintain Order
Ensure the final reservation list remains sorted and non-overlapping
Key Takeaway
๐ฏ Key Insight: Since intervals are pre-sorted and disjoint, we can process them linearly, making intelligent decisions about splits and removals in a single pass - achieving optimal O(n) performance.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code