KatInterview

435. Non-overlapping Intervals

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum number of intervals to remove from a given collection so that the remaining intervals are non-overlapping. An interval [a, b] and [c, d] are non-overlapping if b <= c or d <= a. The core challenge is to identify which intervals to keep and which to discard.

Solution

Non-overlapping Intervals in Python

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        # If there are 0 or 1 intervals, no removals are needed.
        if not intervals:
            return 0

        # Sort intervals based on their end points in ascending order.
        # This is the core of the greedy strategy.
        intervals.sort(key=lambda x: x[1])

        # The number of intervals we can keep without overlapping.
        # We always keep the first interval (the one with the earliest end time).
        kept_count = 1
        # The end point of the last kept interval.
        last_end = intervals[0][1]

        # Iterate through the rest of the intervals.
        for i in range(1, len(intervals)):
            # If the start of the current interval is not before the end of the last kept interval,
            # it means they are non-overlapping.
            if intervals[i][0] >= last_end:
                # We can keep this interval.
                kept_count += 1
                # Update the end point to the current interval's end.
                last_end = intervals[i][1]
            # If they overlap, we do nothing. By sorting by end times, we are implicitly
            # discarding the current interval because it ends later than the one we kept.

        # The number of intervals to remove is the total number minus the ones we kept.
        return len(intervals) - kept_count

Non-overlapping Intervals in Java

class Solution {
    public int eraseOverlapIntervals(int[][] intervals) {
        // If there are 0 or 1 intervals, no removals are needed.
        if (intervals.length <= 1) {
            return 0;
        }

        // Sort intervals based on their end points in ascending order.
        // This is the core of the greedy strategy.
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));

        // The number of intervals we can keep without overlapping.
        // We always keep the first interval (the one with the earliest end time).
        int keptCount = 1;
        // The end point of the last kept interval.
        int lastEnd = intervals[0][1];

        // Iterate through the rest of the intervals.
        for (int i = 1; i < intervals.length; i++) {
            // If the start of the current interval is not before the end of the last kept interval,
            // it means they are non-overlapping.
            if (intervals[i][0] >= lastEnd) {
                // We can keep this interval.
                keptCount++;
                // Update the end point to the current interval's end.
                lastEnd = intervals[i][1];
            }
            // If they overlap, we do nothing. By sorting by end times, we are implicitly
            // discarding the current interval because it ends later than the one we kept.
        }

        // The number of intervals to remove is the total number minus the ones we kept.
        return intervals.length - keptCount;
    }
}

Non-overlapping Intervals in C++

class Solution {
public:
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        // If there are 0 or 1 intervals, no removals are needed.
        if (intervals.size() <= 1) {
            return 0;
        }

        // Sort intervals based on their end points in ascending order.
        // This is the core of the greedy strategy.
        sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) {
            return a[1] < b[1];
        });

        // The number of intervals we can keep without overlapping.
        // We always keep the first interval (the one with the earliest end time).
        int kept_count = 1;
        // The end point of the last kept interval.
        int last_end = intervals[0][1];

        // Iterate through the rest of the intervals.
        for (size_t i = 1; i < intervals.size(); ++i) {
            // If the start of the current interval is not before the end of the last kept interval,
            // it means they are non-overlapping.
            if (intervals[i][0] >= last_end) {
                // We can keep this interval.
                kept_count++;
                // Update the end point to the current interval's end.
                last_end = intervals[i][1];
            }
            // If they overlap, we do nothing. By sorting by end times, we are implicitly
            // discarding the current interval because it ends later than the one we kept.
        }

        // The number of intervals to remove is the total number minus the ones we kept.
        return intervals.size() - kept_count;
    }
};

Non-overlapping Intervals in TypeScript

function eraseOverlapIntervals(intervals: number[][]): number {
    // If there are 0 or 1 intervals, no removals are needed.
    if (intervals.length <= 1) {
        return 0;
    }

    // Sort intervals based on their end points in ascending order.
    // This is the core of the greedy strategy.
    intervals.sort((a, b) => a[1] - b[1]);

    // The number of intervals we can keep without overlapping.
    // We always keep the first interval (the one with the earliest end time).
    let keptCount = 1;
    // The end point of the last kept interval.
    let lastEnd = intervals[0][1];

    // Iterate through the rest of the intervals.
    for (let i = 1; i < intervals.length; i++) {
        // If the start of the current interval is not before the end of the last kept interval,
        // it means they are non-overlapping.
        if (intervals[i][0] >= lastEnd) {
            // We can keep this interval.
            keptCount++;
            // Update the end point to the current interval's end.
            lastEnd = intervals[i][1];
        }
        // If they overlap, we do nothing. By sorting by end times, we are implicitly
        // discarding the current interval because it ends later than the one we kept.
    }

    // The number of intervals to remove is the total number minus the ones we kept.
    return intervals.length - keptCount;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.