</>

435. Non-overlapping Intervals

Medium NeetCode 150
Intervals Time O(n log n) Space O(1)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Intervals
Time
O(n log n)
Space
O(1)

Standard Solution (C++)

SummaryFind the minimum number of intervals to delete so the remaining intervals do not overlap.

Approach

Key idea: This is the classic activity-selection problem. Keeping the most non-overlapping intervals (by always choosing the one that ends earliest) minimizes deletions.

Steps:

  • Sort intervals by end time.
  • Track the end of the last kept interval; if the next interval starts at or after it, keep it and update the end.
  • Otherwise it overlaps, so count it as a deletion.
class Solution {
public:
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) {
            return a[1] < b[1];
        });
        int removed = 0;
        long prevEnd = LONG_MIN;
        for (auto& iv : intervals) {
            if (iv[0] >= prevEnd) {
                prevEnd = iv[1];
            } else {
                ++removed;
            }
        }
        return removed;
    }
};
Time O(n log n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern