Remove one point from a cover of integer intervals
You are given a list of non-overlapping half-open intervals. An interval [start, end] with start < end covers the integers start, start + 1, ..., end - 1. Reading the intervals in the order they are given, and each interval from left to right, produces a flattened sequence of covered integers. The list is not necessarily sorted.
Implement remove_covered_point(intervals, idx), which removes the integer at 0-based position idx of the flattened sequence and returns the resulting list of intervals.
- Keep the input order. Do not sort or merge intervals.
- Removing a point from the middle of an interval splits it into two intervals.
- Never return an empty interval (
start == end). - Raise an error if
idxis negative or not less than the number of covered integers. - Intervals can be very long (lengths up to
10^9), so do not expand them into points.
Example 1
intervals = [[10, 13], [2, 4]] # flattened: 10, 11, 12, 2, 3
idx = 1 # removes 11
-> [[10, 11], [12, 13], [2, 4]]
Example 2
intervals = [[5, 6], [0, 2]] # flattened: 5, 0, 1
idx = 0 # removes 5; its interval disappears
-> [[0, 2]]
Part 2. The same cover now receives many removals in a row. Support remove(idx) (returns the removed integer) and to_intervals() efficiently.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
