Remove Interval Problem
Description
LeetCode Problem 1272.
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] = [a_i, b_i] represents the interval [a_i, b_i). 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.*
Example 1:

Input: intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
Output: [[0,1],[6,7]]
Example 2:

Input: intervals = [[0,5]], toBeRemoved = [2,3]
Output: [[0,2],[3,5]]
Example 3:
Input: intervals = [[-5,-4],[-3,-2],[1,2],[3,5],[8,9]], toBeRemoved = [-1,4]
Output: [[-5,-4],[-3,-2],[4,5],[8,9]]
Constraints:
1 <= intervals.length <= 10^4-10^9 <= a_i < b_i <= 10^9
Solution
Approach: Cut Each Interval
Let the interval to remove be [x, y). Each interval [a, b) of the set can be handled on its own:
- If
b <= xora >= y, it does not overlap[x, y)at all, so we keep it whole. Since intervals are half-open,[0, 2)and[2, 3)only touch and do not overlap. - Otherwise they overlap, and what is left of
[a, b)is at most two pieces:[a, x)ifa < x(a part sticks out on the left), and[y, b)ifb > y(a part sticks out on the right). If neither holds, the whole interval is covered and disappears.
The input intervals are sorted and disjoint, and the pieces of one interval stay inside it in left-to-right order, so appending them as we go gives a sorted list of disjoint intervals without any extra sorting.
Complexity: O(n) time for n intervals, and O(1) extra space besides the output.
class Solution:
def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]:
x, y = toBeRemoved
answer = []
for a, b in intervals:
if b <= x or a >= y:
answer.append([a, b]) # no overlap: keep it whole
else:
if a < x:
answer.append([a, x]) # the part left of the cut
if b > y:
answer.append([y, b]) # the part right of the cut
return answer