Browse curriculum

Non-overlapping Intervals (LeetCode 435)

Non-overlapping Intervals (LeetCode 435): find the minimum number of intervals to remove to eliminate all overlaps.

Problem Understanding

Each entry of intervals is a pair [start, end]. Return the fewest intervals you have to delete so that none of the remaining ones overlap. Intervals that only touch at an endpoint, like [1,2] and [2,3], do not count as overlapping.

Example 1:

  • Input: [[1,2],[2,3],[3,4],[1,3]]
  • Output: 1
  • Explanation: Remove [1,3] to handle the overlaps with [1,2] and [2,3].

Algorithm Strategy

This is a classic Greedy problem. Removing as few intervals as possible is the same as keeping as many as possible, and the interval that finishes earliest leaves the most room for everything after it.

  1. Sort by End Time: Sort intervals by end ascending.
  2. Keep the first: It ends earliest, so keep it and set prevEnd to its end.
  3. Check each later interval curr:
    • If curr.start >= prevEnd, it does not overlap the last kept interval: keep it and set prevEnd = curr.end.
    • Otherwise it overlaps. Because of the sort, curr ends no earlier than the interval already kept, so keeping that one never leaves less room: remove curr and add 1 to the count.
  4. Return the count.

Interactive Visualization

4 INTERVALS

INPUT

intervals · as given

[1,2]

[2,3]

[3,4]

[1,3]

1

4

prevEnd

:

Kept

0

Removed

0

 

4 intervals: remove as few as possible so none overlap

Next

Sort by end time: [[1,2], [2,3], [1,3], [3,4]]: the interval that finishes first leaves the most room

Free preview: the first 3 of 7 steps

Intervals

See how sorting by End Time allows us to reliably pick the 'best' intervals to keep.

Dry Run

Input: [[1,2], [2,3], [3,4], [1,3]]

Step Interval End Time Decision Count
Init - - Sort by End: [[1,2], [2,3], [1,3], [3,4]] 0
1 [1,2] 2 Keep. prevEnd = 2. 0
2 [2,3] 3 Start 2 >= prev 2. Keep. prevEnd = 3. 0
3 [1,3] 3 Start 1 < prev 3. Overlap! Remove. 1
4 [3,4] 4 Start 3 >= prev 3. Keep. prevEnd = 4. 1

Edge Cases & Common Mistakes

  • Equal End Times: The sort order for same end times doesn't affect correctness for count, though sorting by start (secondary) produces consistent selection.
  • Touching Intervals: [1,2] and [2,3] do NOT overlap. Logic must use >=.
  • Negative Numbers: Intervals can have negative coordinates.

Solution

Greedy optimization O(N log N).

Non-overlapping Intervals Code
1var eraseOverlapIntervals = function(intervals) {
2 if (!intervals.length) return 0;
3 intervals.sort((a, b) => a[1] - b[1]);
4
5 let count = 0;
6 let prevEnd = intervals[0][1];
7
8 for (let i = 1; i < intervals.length; i++) {
9 if (intervals[i][0] >= prevEnd) {
10 prevEnd = intervals[i][1];
11 } else {
12 count++;
13 }
14 }
15 return count;
16};

Non-overlapping Intervals in Python, Java, C++, TypeScript and C

Non-overlapping Intervals in Python
def eraseOverlapIntervals(intervals):
    if not intervals: return 0
    # Sort by end time
    intervals.sort(key=lambda x: x[1])

    count = 0
    prev_end = intervals[0][1]

    for i in range(1, len(intervals)):
        if intervals[i][0] >= prev_end:
            prev_end = intervals[i][1]
        else:
            count += 1

    return count
Non-overlapping Intervals in Java
class Solution {
    public int eraseOverlapIntervals(int[][] intervals) {
        if (intervals.length == 0) return 0;
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
        int count = 0;
        int prevEnd = intervals[0][1];
        
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] >= prevEnd) {
                prevEnd = intervals[i][1];
            } else {
                count++;
            }
        }
        return count;
    }
}
Non-overlapping Intervals in C++
class Solution {
public:
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        if (intervals.empty()) return 0;
        sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) {
            return a[1] < b[1];
        });
        
        int count = 0;
        int prevEnd = intervals[0][1];
        
        for (int i = 1; i < intervals.size(); i++) {
            if (intervals[i][0] >= prevEnd) {
                prevEnd = intervals[i][1];
            } else {
                count++;
            }
        }
        return count;
    }
};
Non-overlapping Intervals in TypeScript
function eraseOverlapIntervals(intervals: number[][]): number {
    if (!intervals.length) return 0;
    intervals.sort((a, b) => a[1] - b[1]);
    
    let count = 0;
    let prevEnd = intervals[0][1];
    
    for (let i = 1; i < intervals.length; i++) {
        if (intervals[i][0] >= prevEnd) {
            prevEnd = intervals[i][1];
        } else {
            count++;
        }
    }
    return count;
};
Non-overlapping Intervals in C
int compare(const void* a, const void* b) {
    return ((int**)a)[0][1] - ((int**)b)[0][1];
}

int eraseOverlapIntervals(int** intervals, int intervalsSize, int* intervalsColSize) {
    if (intervalsSize == 0) return 0;
    qsort(intervals, intervalsSize, sizeof(int*), compare);
    
    int count = 0;
    int prevEnd = intervals[0][1];
    
    for (int i = 1; i < intervalsSize; i++) {
        if (intervals[i][0] >= prevEnd) {
            prevEnd = intervals[i][1];
        } else {
            count++;
        }
    }
    return count;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Sort by end

    Sort the intervals by end time and keep the first one.

  2. Keep or remove

    Keep an interval when it starts at or after prevEnd and move prevEnd to its end; otherwise count it as removed.

  3. Return the count

    Return how many intervals were removed.

Frequently asked questions

Why sort by end time for Non-overlapping Intervals?

Keeping the interval that finishes first leaves the most room for the rest. Sorting by end lets one pass keep every interval that fits and remove the others, which removes as few as possible.


Do [1,2] and [2,3] overlap in this problem?

No. An interval is kept when its start is greater than or equal to the last kept end, so intervals that only touch are both kept.


What is the time complexity?

O(n log n) for the sort and O(n) for the pass. Apart from the sort, it uses O(1) extra space.

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description