15% off all plans & roadmaps Use code

See plans

Non-overlapping Intervals

Updated

TL;DR: Find the largest set of intervals that do not overlap, then remove everything else. Sort by end point and greedily keep each interval that starts at or after the last kept end.

Problem

You are given an array intervals, where each intervals[i] = [start, end] describes one interval. Two intervals overlap when they share an interior portion. Intervals that only meet at an endpoint, such as [1,3] and [3,6], do not overlap.

Remove as few intervals as you can so that every pair of remaining intervals is non-overlapping. Return the minimum number of intervals you must remove.

Example 1

Input: intervals = [[1,3],[3,6],[6,10]]
Output: 0
Explanation: Each interval only touches the next one at an endpoint, so none of them overlap.

Example 2

Input: intervals = [[1,4],[2,3],[5,7],[6,8]]
Output: 2
Explanation: One interval must go from each overlapping pair. For instance, keep [2,3] and [5,7].

Example 3

Input: intervals = [[1,10],[2,4],[3,7],[8,9]]
Output: 2
Explanation: [1,10] overlaps all three shorter intervals, and [2,4] overlaps [3,7]. Removing [1,10] and one of [2,4] or [3,7] leaves a non-overlapping set.

Constraints

  • 1 <= intervals.length <= 10^5
  • intervals[i].length == 2
  • start < end for every interval
  • 1 <= start <= 5 * 10^4
  • 1 <= end <= 5 * 10^4

Constraints that matter

  • n up to 10^5 rules out any approach that tries subsets (2^n). It also rules out the O(n^2) pairwise DP, which needs about 10^10 steps.
  • An O(n log n) sort followed by one linear scan fits comfortably, so the answer is a sort plus a greedy pass.
  • start < end means every interval has positive length, so there are no zero-width intervals to special-case.
  • Coordinates are at most 5 * 10^4, so there is no integer overflow in any language. A sentinel such as 0 or a minimum integer is safe for the initial boundary.
  • At least one interval is always present, so the list is never empty and a first interval always exists.

View on LeetCode

Hints

Hint 1

Removing the fewest intervals is the same as keeping the most intervals.

Hint 2

Treat it as a pure choice problem.

Solution

Intuition

Removing the fewest intervals is the same as keeping the most intervals. So the question becomes: what is the largest set of pairwise non-overlapping intervals? This is the interval scheduling problem, and the pattern is a greedy choice after sorting.

Picture one meeting room with a booking calendar. The variable lastEnd is the time the room next becomes free, and you book any meeting that starts at or after that time.

Think of the timeline as a single room where you want to book as many meetings as possible. The meeting that frees the room earliest leaves the most time for everything after it. That points to sorting by end point, not by start point.

Why does it work? Suppose two intervals both fit as the next pick, and one ends earlier. Anything that can follow the later-ending interval can also follow the earlier-ending one, because it only needs to start at or after a smaller number. Swapping in the earlier-ending interval never shrinks the final set, so you can always take it.

The overlap test is start < lastEnd. Equal values mean the intervals touch, which is legal, so the keep condition is start >= lastEnd.

Watch the pattern animation

Worked example

Input: intervals = [[1,3],[3,6],[6,10]]
Output: 0
Explanation: Each interval starts exactly where the previous one ends. Touching at an endpoint is allowed, so all three intervals stay and nothing is removed.

Approach 1: Brute force: try keep or drop for every interval

Treat it as a pure choice problem. For each interval you either keep it or drop it, and you want the largest kept set that has no overlaps. Sort by start so you decide intervals left to right, and carry the end of the last kept interval. An interval can be kept only if its start is at or after that end.

This is correct because every subset is explored, but it is exponential.

Steps

  1. Sort the intervals by start.
  2. Define best(i, prevEnd) as the largest number of intervals you can keep from index i onward, given the last kept interval ended at prevEnd.
  3. If i equals n, return 0.
  4. Compute the drop option: best(i + 1, prevEnd).
  5. If intervals[i][0] >= prevEnd, compute the keep option: 1 + best(i + 1, intervals[i][1]).
  6. Return the larger of the two options.
  7. Answer n - best(0, 0).

Dry run

Take [[1,3],[3,6],[6,10]], already sorted by start. Call best(0, 0).

  • Interval [1,3]: start 1 >= 0, so keeping is allowed. The call best(1, 3) runs next.
  • Interval [3,6]: start 3 >= 3, so keeping is allowed. The call best(2, 6) runs next.
  • Interval [6,10]: start 6 >= 6, so keep it. best(3, 10) returns 0, so this branch returns 1.
  • Going back up, the keep-everything branch yields 3. Drop branches yield at most 2.

The largest kept set is 3, so the answer is 3 - 3 = 0. The recursion visits up to 2^3 = 8 leaves here, but 2^100000 on a worst-case input.

Complexity

TimeO(2^n)
SpaceO(n)

Here n is the number of intervals. Each interval has two choices, so the recursion tree has up to 2^n leaves. The recursion depth is n, so the call stack uses O(n) space. The sort adds only O(n log n) time, which is dominated.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        intervals.sort()
        n = len(intervals)

        def best(i: int, prev_end: int) -> int:
            if i == n:
                return 0
            res = best(i + 1, prev_end)  # drop interval i
            if intervals[i][0] >= prev_end:  # keep interval i
                res = max(res, 1 + best(i + 1, intervals[i][1]))
            return res

        return n - best(0, 0)

Approach 2: Dynamic programming over sorted starts

What's slow: the recursion recomputes the same state many times. The answer for best(i, prevEnd) depends only on which interval was kept last, not on the path that led there. So there are only n distinct states that matter.

The insight that fixes it: define dp[i] as the largest non-overlapping chain that ends with interval i. After sorting by start, any earlier interval j can precede i when end_j <= start_i. Take the best such dp[j] and add one. This is the longest chain pattern.

Steps

  1. Sort the intervals by start.
  2. Create dp of length n, filled with 1, since each interval alone is a chain of length 1.
  3. For each i, scan every j < i.
  4. If intervals[j][1] <= intervals[i][0], set dp[i] = max(dp[i], dp[j] + 1).
  5. Track the maximum dp[i] as kept.
  6. Return n - kept.

Dry run

On [[1,3],[3,6],[6,10]] sorted by start, dp starts as [1, 1, 1].

  • i = 1: check j = 0. End 3 <= start 3, so dp[1] = dp[0] + 1 = 2.
  • i = 2: check j = 0. End 3 <= start 6, so dp[2] = 2. Check j = 1. End 6 <= start 6, so dp[2] = dp[1] + 1 = 3.

The maximum is 3, so kept = 3 and the answer is 3 - 3 = 0.

Complexity

TimeO(n^2)
SpaceO(n)

Here n is the number of intervals. The nested loops compare each pair (j, i) with j < i once, which is n * (n - 1) / 2 comparisons. The dp array holds one integer per interval, so space is O(n). With n = 10^5 this is about 5 * 10^9 comparisons, too slow.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        intervals.sort()
        n = len(intervals)
        dp = [1] * n  # dp[i]: longest chain ending at interval i
        kept = 1
        for i in range(n):
            for j in range(i):
                if intervals[j][1] <= intervals[i][0]:
                    dp[i] = max(dp[i], dp[j] + 1)
            kept = max(kept, dp[i])
        return n - kept
Interval Merging/Scheduling pattern infographic for Non-overlapping Intervals

Solution pattern

Interval Merging/Scheduling

Part of Greedy Patterns

Approach 3: Greedy: sort by end, keep the earliest finisherOptimalInterval Merging/Scheduling

What's slow: the DP checks every earlier interval to find the best predecessor. Most of that work is wasted, because the best choice is already known. The interval that ends first leaves the most room, so you never need to compare alternatives.

The insight that fixes it: sort by end point. Scan once and keep an interval whenever its start is at or after lastEnd. If it starts earlier, it overlaps a kept interval that ends no later than it does, so dropping it is never worse. Only a kept interval moves lastEnd.

Why it is correct. The invariant: after each step, kept is the largest count possible so far, and lastEnd is the smallest end achieving that count. Skipping an interval that starts too early never hurts, because a kept interval already ends no later than it does. So the greedy pick never loses a better answer.

Steps

  1. Sort the intervals by end point, smallest first.
  2. Set lastEnd to a value below every start, such as 0, and kept to 0.
  3. For each interval in order, compare its start with lastEnd.
  4. If start >= lastEnd, keep it: add 1 to kept and set lastEnd to its end.
  5. Otherwise skip it and leave lastEnd unchanged.
  6. Return n - kept.

Dry run

On [[1,3],[3,6],[6,10]], the ends are already 3, 6, 10, so the sorted order is unchanged. Start with lastEnd = 0, kept = 0.

StepIntervalstart >= lastEnd?ActionlastEndkept
0(start)00
1[1,3]1 >= 0 yeskeep31
2[3,6]3 >= 3 yeskeep62
3[6,10]6 >= 6 yeskeep103

The answer is n - kept = 3 - 3 = 0. Each interval touches the previous end exactly, so the >= test is what keeps all three.

For contrast, take [[1,10],[2,4],[3,7],[8,9]]. The sorted order is [2,4],[3,7],[8,9],[1,10]. Keep [2,4], skip [3,7] since 3 < 4, keep [8,9] since 8 >= 4, skip [1,10] since 1 < 9. Kept is 2, so the answer is 4 - 2 = 2.

Complexity

TimeO(n log n)
SpaceO(1)

Here n is the number of intervals. Sorting costs O(n log n) and the scan visits each interval once, which is O(n), so sorting dominates. Beyond the sort, the algorithm stores only lastEnd and kept, so extra space is O(1). The sort itself may use O(log n) to O(n) internal memory depending on the language.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        intervals.sort(key=lambda iv: iv[1])  # earliest end first
        kept = 0
        last_end = 0  # every start is >= 1, so 0 accepts the first interval
        for start, end in intervals:
            if start >= last_end:  # touching at an endpoint is allowed
                kept += 1
                last_end = end
        return len(intervals) - kept

Common mistakes

  • Sorting by start with sort(key=lambda iv: iv[0]) and then greedily keeping. A long early interval such as [1,10] blocks many short ones. Sort by end instead.
  • Using start > lastEnd (or start <= lastEnd as the overlap test). Intervals that touch at an endpoint are legal, so the keep condition must be start >= lastEnd.
  • Updating lastEnd = end for a skipped interval. A skipped interval is removed, so it must not move the boundary. Only update lastEnd inside the keep branch.
  • Returning kept instead of n - kept. The problem asks for the number removed, so subtract the kept count from len(intervals).
  • Initializing lastEnd to the first interval's end but still running the loop from index 0. The first interval then looks like it overlaps itself when start < end. Either start the loop at index 1 or use a sentinel below every start.
  • Comparing with a[1] - b[1] in a sort for huge values in typed languages. Here values are at most 5 * 10^4, so it is safe. Still, Integer.compare is the habit that avoids overflow bugs elsewhere.

Edge cases

  • A single interval [[1,2]]: nothing can overlap, so the answer is 0.
  • Intervals that only touch, [[1,3],[3,6],[6,10]]: the answer is 0, because shared endpoints are allowed.
  • Identical intervals [[1,2],[1,2],[1,2]]: keep one and remove two, so the answer is 2.
  • One interval covering all others, [[1,10],[2,4],[3,7],[8,9]]: remove [1,10] and one of the two middle ones, giving 2.
  • Already sorted and fully nested, [[1,100],[2,50],[3,10]]: keep the innermost [3,10], answer 2.
  • Maximum size, 10^5 intervals: the O(n log n) sort and one scan finish quickly, while recursion or an O(n^2) DP would time out.

Follow-ups interviewers ask

Why does sorting by start time with the same greedy fail?
An interval with an early start can end very late. Keeping it blocks many short intervals that fit inside it, as in [1,10] versus [2,4], [8,9]. The kept boundary is no longer as small as possible, so you may remove too many. Sorting by start works only if you also handle conflicts by dropping the interval with the larger end, which is the same greedy rule in disguise.
Can you do it without sorting by end, using sort by start and one scan?
Yes. Sort by start. When the current interval overlaps the last kept one, remove one of them: keep the one with the smaller end, set lastEnd = min(lastEnd, end), and count a removal. This gives the same answer in O(n log n), because the min rule is the same earliest-finish choice.
What if you must return which intervals to remove, not only the count?
Record the index or the interval itself whenever the greedy skips it. Sort indices by end instead of sorting the array in place, so you can map back to the original order. The extra output is O(n) space and the time stays O(n log n).

Non-overlapping Intervals FAQ

What is the time complexity of Non-overlapping Intervals?

The greedy solution runs in O(n log n) time, where n is the number of intervals. Sorting by end costs O(n log n) and the single scan costs O(n). Extra space is O(1) beyond the sort.

Why use a greedy approach for Non-overlapping Intervals?

Removing the fewest intervals means keeping the most. The interval that ends earliest leaves the largest remaining timeline, so choosing it never hurts a later choice. That exchange argument makes the greedy pick optimal, which lets you skip the DP.

How do you check whether two intervals overlap?

Two intervals [a, b] and [c, d] overlap when a < d and c < b. In this problem, touching at an endpoint is not an overlap. After sorting by end, the check reduces to start < lastEnd.

Why sort by end time instead of start time?

Sorting by end lets you decide each interval with one comparison against the last kept end. An interval with a late end can only hurt later choices, so the earlier end is always preferred. Sorting by start gives a long early interval priority it does not deserve.

Can Non-overlapping Intervals be solved in O(1) extra space?

Almost. The scan itself uses O(1) extra space, but you must sort first. In-place sorting such as heap sort uses O(1) extra space, while the built-in sorts of Python, Java and others use O(log n) to O(n) internally. The sort also mutates the input unless you copy it.

What is the difference between Non-overlapping Intervals and Merge Intervals?

Merge Intervals combines overlapping intervals into larger ones and sorts by start. Non-overlapping Intervals chooses which intervals to delete so the rest do not overlap, and the best greedy sorts by end. Both begin with a sort and a single pass.

Asked at

See which companies ask this — Pro

Practise it