Tensorum
LeetCode 435 · Intervals

Non-overlapping Intervals

LeetCode 435 · Medium · solution, intuition & step-by-step walkthrough

Sort by end; count overlaps with the last kept.

MediumArrayDynamic ProgrammingGreedySorting
71 msruntime · beats 70%
51.3 MBmemory · beats 10%
1approach
1accepted runs · last 14 Jun 2025

This is how I solved Non-overlapping Intervals (LeetCode 435), a medium problem from the Intervals pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

To keep as many intervals as possible, always keep the one that ends earliest — it leaves the most room for the rest. Sort by end; every interval that starts before the last kept end has to be removed.

Approach

  1. 1

    Sort by end time.

  2. 2

    If start ≥ last end, keep it and update the end.

  3. 3

    Otherwise remove it (count++).

How I solved it

Greedy by end timePythonO(n log n) time
class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        lastend=-inf
        #sort by end time
        intervals.sort(key=lambda x:x[1])
        ans = 0
        for start,end in intervals:
            if start>=lastend:
                lastend=end
            else:
                ans+=1
        return ans
Loading the step-through…

Non-overlapping Intervals — FAQ

What is the intuition behind Non-overlapping Intervals?

To keep as many intervals as possible, always keep the one that ends earliest — it leaves the most room for the rest. Sort by end; every interval that starts before the last kept end has to be removed.

How do you solve Non-overlapping Intervals (LeetCode 435)?

1. Sort by end time. 2. If start ≥ last end, keep it and update the end. 3. Otherwise remove it (count++).

What is the time and space complexity of Non-overlapping Intervals?

Time: O(n log n). Space: O(1). (Accepted approach: Greedy by end time.)

What are common mistakes in Non-overlapping Intervals?

Sorting by start instead needs extra logic to keep the smaller end.