Non-overlapping Intervals solution explained

Non-overlapping Intervals asks for the fewest ranges to delete so that none of the rest overlap. Flip it around: keep as many ranges as possible. Sort by end time, keep a range whenever it starts at or after the end of the last kept range, and the answer is the total minus the number kept. Sorting makes it O(n log n).

By Published 7 min read

The problem, reworded

Each item is a [start, end] pair with start strictly less than end. Two ranges clash if they share more than a single point; a range ending at 4 and another starting at 4 do not clash. Remove as few ranges as possible so that no two remaining ranges clash, and return how many you removed.

Ranges made up for this page, with answers from the code below
RangesFewest removalsOne set you can keep
[[0, 4], [1, 3], [3, 6], [5, 8], [7, 9]]2[1, 3], [3, 6], [7, 9]
[[1, 10], [2, 3], [4, 5], [6, 7]]1Drop the long one, keep the three short ones
[[0, 2], [2, 4], [4, 6]]0They only touch, so nothing clashes
[[3, 7], [3, 7], [3, 7]]2Identical copies: keep one
Ranges made up for this page, with answers from the code below. Scroll sideways on a small screen.

Note the contrast with Merge Intervals and Insert Interval, whose examples treat touching ranges as overlapping. Here, as in most scheduling problems, the convention is half-open: a meeting that ends at 4 frees the slot for one that starts at 4. Confirm it before you code, because it changes one comparison.

Why interviewers use it

This is the cleanest test of whether you can pick the right greedy key and defend it. Three sort orders look plausible: by start, by length, and by end. Only one is safe, and the interviewer wants to hear why the other two fail and why the third cannot. Candidates who sort by end from memory but cannot give the exchange argument usually get pushed on it.

Greedy keys that fail

  • Sort by start, keep whatever comes first. On the second example, [1, 10] comes first and blocks the three short ranges, so this keeps 1 and removes 3. The correct answer removes 1.
  • Sort by length, keep the shortest first. A short range can sit across the boundary of two longer ranges that would otherwise both fit. For example, with [0, 5], [4, 7] and [6, 11], the short [4, 7] clashes with both others, so keeping it first leaves only one range, while dropping it keeps two.
  • Sort by end, keep the earliest finisher. This one is safe, and the reason is below.

A correct baseline: longest compatible chain

Sort by start. For each range i, compute the longest chain of non-clashing ranges that ends with i, by checking every earlier range j whose end is at or before i's start. The best chain length is the most you can keep. Checking every subset would be exponential; this table is O(n²), which is fine to describe and useful as a reference.

def fewest_removals_dp(ranges):
    spans = sorted(ranges)
    longest = [1] * len(spans)  # longest compatible chain ending at i
    for i in range(len(spans)):
        for j in range(i):
            if spans[j][1] <= spans[i][0]:
                longest[i] = max(longest[i], longest[j] + 1)
    return len(spans) - max(longest, default=0)
Python: chain table over ranges sorted by start. O(n²).

The greedy: keep the range that frees up earliest

Sort by end. Walk the ranges, remembering the end of the last range you kept. If the next range starts at or after that end, keep it and update the end. Otherwise it clashes with something you kept, so count it as removed. Since ranges arrive in order of end time, every range you keep is the one that leaves the most room for whatever comes after.

def fewest_removals(ranges):
    kept = 0
    free_at = float("-inf")  # end of the last range we kept
    for start, end in sorted(ranges, key=lambda r: r[1]):
        if start >= free_at:  # touching counts as no clash
            kept += 1
            free_at = end
    return len(ranges) - kept
Python: sort by end, then one pass. O(n log n) time.
#include <algorithm>
#include <climits>
#include <vector>
using namespace std;

int fewestRemovals(vector<vector<int>> ranges) {
    sort(ranges.begin(), ranges.end(),
         [](const vector<int>& x, const vector<int>& y) { return x[1] < y[1]; });
    int kept = 0;
    long long freeAt = LLONG_MIN;
    for (const auto& r : ranges) {
        if (r[0] >= freeAt) {
            ++kept;
            freeAt = r[1];
        }
    }
    return (int)ranges.size() - kept;
}
C++: same logic. The ranges are taken by value so the caller's order is kept.

Trace on the first example

Sorted by end: [1, 3], [0, 4], [3, 6], [5, 8], [7, 9]. Keep [1, 3], so the slot is free from 3. [0, 4] starts at 0, before 3: removed. [3, 6] starts exactly at 3: kept, free from 6. [5, 8] starts at 5, before 6: removed. [7, 9] starts at 7: kept. Three kept out of five, so two removals.

Why the earliest finisher is always safe

Take any best possible set of kept ranges and look at the one in it that ends first. Call the range with the earliest end overall E. Replace that first range with E. E ends no later than the range it replaced, so it cannot clash with anything that came after in the set. The set is still valid and the same size. Repeat the argument on the ranges that start at or after E's end, and you rebuild exactly what the greedy picks. No optimal set beats it.

The same argument also justifies a variant some people prefer: sort by start, and when two ranges clash, drop the one that ends later. It makes the same choices in a different order.

Complexity

n ranges
ApproachTimeExtra space
Try every subsetO(2ⁿ · n)O(n)
Chain table after sorting by startO(n²)O(n)
Sort by end, greedy passO(n log n)O(1) beyond the sort
n ranges. Scroll sideways on a small screen.

Edge cases

  • No ranges or a single range: 0 removals.
  • Ranges that touch end to start: all kept under the half-open convention.
  • Exact duplicates: all but one are removed.
  • Negative or very large coordinates: only comparisons are used, so nothing changes. In C++, start the last-kept end below any possible start, which is why the code uses the smallest long long.
  • Many ranges ending at the same time: their order among themselves does not affect the count when every range has positive length.

Common slips

  • Sorting by start and keeping the first range of every clash.
  • Using a strict comparison where the half-open rule needs start at or after the last end, which removes ranges that only touch.
  • Returning the number kept instead of the number removed.
  • Initializing the last-kept end to 0, which wrongly removes ranges with negative starts.

Follow-up questions

  • Return the ranges to remove, not just the count. Collect each range the greedy skips.
  • Each range has a value, and you want the most total value kept. The greedy fails; use the chain table with binary search on end times, which is weighted interval scheduling in O(n log n).
  • How many arrows does it take to burst ranges, where one arrow hits every range covering a point? Same sort by end; shoot at the end of the first unhit range.
  • Can one person attend every meeting? That is the zero-removals check, covered on Meeting Rooms.

Putting it into words

Fictional example

A spoken version of the answer
Candidate
Removing the fewest is the same as keeping the most, so I'll count the largest set of ranges that don't clash and subtract.
Candidate
I sort by end and keep a range if it starts at or after the last kept end. Sorting by start fails when a long range comes first, so the end time is the right key.
Candidate
Why it's safe: in any optimal set I can swap the first range for the one that ends earliest overall without creating a clash. That gives O(n log n) for the sort and a linear pass.

Meeting Rooms asks only whether any clash exists. Insert Interval merges clashes instead of deleting them, and Partition Labels is another greedy where choosing the earliest safe cut is the whole proof. The coding problems hub has the rest.

How Natively fits into practice

Practicing on Mac or Windows, you can share this problem with Natively through a screenshot and ask it for a case where sorting by start or by length goes wrong, then check your exchange argument against it. The mock session is transcribed and saved with notes, so you can read back whether the proof came across clearly. Read more on the AI interview assistant page.

Questions people ask

How do you solve Non-overlapping Intervals?

Sort the ranges by end. Keep a range if it starts at or after the end of the last kept range, otherwise count it as removed. The answer is the number removed.

Why sort by end time in Non-overlapping Intervals?

The range that ends first leaves the most room for the rest. Any optimal set can swap its first range for the earliest-finishing one without creating a clash, so the greedy is optimal.

Why does sorting by start fail in Non-overlapping Intervals?

A long range that starts first can block several short ones. Keeping it first can force many removals when removing only the long range would be enough.

What is the time complexity of Non-overlapping Intervals?

O(n log n) for the sort plus a linear pass. A chain table over ranges sorted by start is O(n²).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP