Remove Interval — LeetCode 1272 Python Solution

MediumLeetCode PremiumArray
Problem
#1272
Reading time
3 min

The 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.

Example

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

Python solution

Python
class Solution:
    def removeInterval(
        self, intervals: List[List[int]], toBeRemoved: List[int]
    ) -> List[List[int]]:
        x, y = toBeRemoved
        ans = []
        for a, b in intervals:
            if a >= y or b <= x:
                ans.append([a, b])
            else:
                if a < x:
                    ans.append([a, x])
                if b > y:
                    ans.append([y, b])
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the interval list
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1272. Remove Interval?
LeetCode 1272. Remove Interval is rated Medium on LeetCode.
What is the time complexity of LeetCode 1272. Remove Interval?
The Python solution on this page runs in O(n), where n is the length of the interval list.
What is the space complexity of LeetCode 1272. Remove Interval?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1272. Remove Interval cover?
LeetCode 1272. Remove Interval is tagged Array on LeetCode.
Is LeetCode 1272. Remove Interval a premium problem?
Yes. LeetCode 1272. Remove Interval is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview