Search lands in PR-5.1 (Pagefind).

How-to Intermediate

Chapter 1 Updated

Non-Overlapping Intervals

Sort by end, greedily keep the earliest-finishing interval.

  • Full 6m
  • Revision 2m
  • Flow 1m

Problem Statement

Given an array of intervals, return the minimum number of intervals you need to remove so the remaining set is pairwise non-overlapping.

Input

An array of intervals [[start, end], …].

Example inputs
[[1,2],[2,3],[3,4],[1,3]]
[[1,2],[1,2],[1,2]]

Output

A single integer — the minimum count of removals required.

Expected outputs
1
2

Constraints

  • 1 ≤ intervals.length ≤ 10⁵
  • intervals[i].length == 2
  • -5·10⁴ ≤ startᵢ < endᵢ ≤ 5·10⁴

Intuition

This is the Activity Selection Problem in disguise. By sorting by end time, we greedily keep the interval that finishes earliest — leaving the maximum room for future intervals. The number of removals equals totalmax intervals we can keep.

Walkthrough — [[1,2],[2,3],[3,4],[1,3]]
After sort by END:  [[1,2], [2,3], [1,3], [3,4]]
 
Step 1  keep [1,2],   last_end = 2
Step 2  [2,3] → 2 ≥ 2 → no overlap → KEEP,   last_end = 3
Step 3  [1,3] → 1 < 3 → overlap    → REMOVE, count = 1
Step 4  [3,4] → 3 ≥ 3 → no overlap → KEEP
 
Answer:  1 removal

Solution

non_overlapping.py
def eraseOverlapIntervals(intervals: list[list[int]]) -> int:
    if not intervals:
        return 0
 
    # KEY: Sort by END time for greedy
    intervals.sort(key=lambda x: x[1])
 
    count = 0
    last_end = intervals[0][1]
 
    for i in range(1, len(intervals)):
        if intervals[i][0] < last_end:
            count += 1     # overlap → remove this one
        else:
            last_end = intervals[i][1]
 
    return count

Complexity

MetricValueReason
TimeO(n log n)Sorting; the linear scan is O(n)
SpaceO(1)Only tracking last_end and count

Edge Case Thinking

ScenarioHandling
No overlapscount stays 0 → return 0.
All identical intervals [[1,2],[1,2],[1,2]]Keep 1, remove n − 1.
Single intervalReturn 0.
Sort-by-start vs sort-by-endSort by start and a long [1,100] blocks everyone; sort by end keeps the earliest-finishing one.
Touching endpoints [1,2] & [2,3]2 < 2 is false → no conflict → neither is removed.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.