MediumNo. 1272LeetCode Premium

Remove Interval — LeetCode 1272 Python Solution

Topics
Array
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

PythonSolution
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

Time
O(n)where n is the length of the interval list
Space · auxiliary
O(1)

Related problems

Related problems
No.ProblemDifficulty
0057Insert IntervalMedium
0228Summary RangesEasy
0485Max Consecutive OnesEasy
0665Non-decreasing ArrayMedium
0674Longest Continuous Increasing SubsequenceEasy
0699Falling SquaresHard

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.

Free to download. Check it runs on your machine, then pick a plan.