Non-overlapping Intervals

35 min · eraseOverlapIntervals()

A room has too many bookings, and some of them collide. You don't get to move a booking; you can only cancel as few as possible until the schedule is conflict-free.

Given intervals, return the minimum number of intervals to remove so every remaining pair is non-overlapping.

Endpoints may touch without a conflict. [1, 2] followed by [2, 3] is valid because the first interval ends exactly when the second begins.

A few ground rules:

  • Every interval is [start, end] with start < end.
  • The input may arrive in any order and may contain duplicates.
  • You return only the number removed, not the surviving intervals.

Constraints

  • 1 <= intervals.length <= 100_000
  • Every interval has exactly two integers: [start, end].
  • -50_000 <= start < end <= 50_000

Hints

Flip what you count

Minimizing removals is the same as maximizing how many compatible intervals you keep. The answer is total - kept.

Which booking leaves room?

When several intervals compete, keeping the one that ends earliest leaves the most room for everything that follows.

Sort by the decision boundary

Sort by end time. Keep an interval when its start is at least the end of the last kept interval; equality is allowed because touching isn't overlap here.

Follow-up

Can you give an exchange argument: if an optimal schedule keeps a later-ending interval first, why can you replace it with the earliest-ending choice without losing capacity?

Visible cases

Examples

Example 1

ready
Input
intervals = [
  [
    1,
    2
  ],
  [
    2,
    3
  ],
  [
    3,
    4
  ],
  [
    1,
    3
  ]
]
Expected
1
Why
remove [1, 3]; the three shorter intervals then touch without overlapping

Example 2

ready
Input
intervals = [
  [
    1,
    2
  ],
  [
    1,
    2
  ],
  [
    1,
    2
  ]
]
Expected
2
Why
only one of three identical ranges can remain

Example 3

ready
Input
intervals = [
  [
    1,
    2
  ],
  [
    2,
    3
  ]
]
Expected
0
Why
touching at endpoint 2 doesn't create an overlap

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite