InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Intervals

Non-overlapping Intervals

medium Original ↗ 00:00

Problem

You are given a list of intervals [start, end). Remove as few intervals as possible so that the remaining intervals are pairwise non-overlapping, and return that minimum number of removals.

Intervals that only touch do not overlap: [1,2) and [2,3) can coexist. Duplicated intervals are allowed in the input, and duplicates of the same interval do overlap each other.

Examples

  • intervals = [[1,2],[2,3],[3,4],[1,3]]1 — remove [1,3]; the remaining intervals are non-overlapping.
  • intervals = [[1,2],[1,2],[1,2]]2 — three copies of the same interval, so only one can stay.
  • intervals = [[1,2],[2,3]]0 — touching at 2 is fine, nothing to remove.

Constraints

  • 1 <= len(intervals) <= 10^5
  • -5 * 10^4 <= start < end <= 5 * 10^4

n = 10^5 rules out both exponential search and the O(n^2) DP. The intended solution is an O(n log n) greedy.

Think about it first

Hint 1 "Minimum removals" is the same number as n minus the maximum number of intervals you can keep. Maximizing the kept set is the classic activity-selection question.
Hint 2 Suppose you must keep some interval as the first one in your non-overlapping set. Between two candidates that both fit, why is the one that ends earlier never a worse choice?
Hint 3 Sort by end time. Sweep left to right keeping a running "last kept end": keep an interval if its start is ≥ that value (and update it), otherwise count it as removed. Ending earliest leaves maximal room for the future — that exchange argument is the whole proof.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug