DSA AnimatorREVISION VIDEOS
← Back to problems
New

Non-Overlapping Intervals — LeetCode 435 video explanation

Given a list of intervals, remove the fewest intervals so that the rest do not overlap. Intervals that only touch at an end point do not overlap.

Loading videos…

DSA Animator › DSA Revision › Intervals › Non-Overlapping Intervals

Key moments in the Non-Overlapping Intervals video

0:04Problem0:13Example0:20Brute force0:27Key idea0:38Dry run0:53Code1:05Takeaway

What you will learn

Remember: sort by end, and keep the one that finishes first. Removals equal n minus the most intervals you can keep. The video solves Non-Overlapping Intervals (LeetCode 435, Medium) with the Greedy by End pattern from the Intervals topic, and you can replay every step in the interactive Non-Overlapping Intervals animation.

Non-Overlapping Intervals video transcript

Problem

Given a list of intervals, remove the fewest intervals so that the rest do not overlap. Intervals that only touch at an end point do not overlap.

Example

For 1 to 2, 2 to 3, 3 to 4 and 1 to 3, remove just 1 to 3, so the answer is 1.

Brute force

Trying every subset of intervals is exponential. Greedy works: always keep the interval that ends earliest.

Key idea

Sort the intervals by end. Keep an interval if it starts at or after the end of the last kept one. Otherwise it overlaps, so remove it, and the earlier end leaves more room for the rest.

Dry run

Sorted by end: 1 to 2, 2 to 3, 1 to 3, 3 to 4. Keep 1 to 2, then keep 2 to 3, because it starts at 2. 1 to 3 starts before 3, so remove it. 3 to 4 starts at 3, so keep it. One interval was removed.

Code

In code, sort by the end value. Track the end of the last kept interval. If the next start is at least that end, keep it and update the end, otherwise count a removal. It's O of n log n time.

Takeaway

Remember: sort by end, and keep the one that finishes first. Removals equal n minus the most intervals you can keep.

More Intervals revision videos

← All 185 DSA revision videos