InterviewPrepKit

Home / Coding / Intervals

Non-overlapping Intervals

medium Original β†—
Solving tips
  • Reframe 'minimum removals' as n minus the maximum kept set: this is classic activity selection.
  • Sort by END time and greedily keep every interval whose start >= last kept end (counting the rest as removed); finishing earliest can never hurt the future (exchange argument).
  • Sorting by END is the key decision here, contrasting with merge/overlap problems that sort by start; a start-sorted greedy needs a fix and is error-prone.
  • Touching is allowed for these half-open intervals, so use '>=' not '>'; target O(n log n) time, O(1) space and avoid the O(n^2) LIS-style DP at n = 10^5.

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] and the rest are a clean chain.
  • intervals = [[1,2],[1,2],[1,2]] β†’ 2 β€” three copies of the same interval; 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 not only exponential search but also the O(n^2) DP β€” the intended solution is 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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.