LeetCode 435: Non-overlapping Intervals Solution

Master LeetCode problem 435 (Non-overlapping Intervals), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

435. Non-overlapping Intervals

Problem Explanation

Explanation

To solve this problem, we can use a greedy approach. We first sort the intervals based on their end points. Then, we iterate through the sorted intervals and maintain an end point variable representing the end of the last non-overlapping interval. If the current interval overlaps with the previous one, we need to remove one of them. We always choose to remove the interval with the larger end point since this would maximize the chances of fitting more intervals.

By following this approach, we can find the minimum number of intervals that need to be removed to make the rest non-overlapping.

  • Time complexity: O(nlogn) where n is the number of intervals
  • Space complexity: O(1)

Solution Code

import java.util.Arrays;

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 = 1;
        int end = intervals[0][1];
        
        for(int i = 1; i < intervals.length; i++) {
            if(intervals[i][0] >= end) {
                count++;
                end = intervals[i][1];
            }
        }
        
        return intervals.length - count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 435 (Non-overlapping Intervals)?

This page provides optimized solutions for LeetCode problem 435 (Non-overlapping Intervals) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 435 (Non-overlapping Intervals)?

The time complexity for LeetCode 435 (Non-overlapping Intervals) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 435 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 435 in Java, C++, or Python.

Back to LeetCode Solutions