Non-overlapping Intervals in Python and Java
In this tutorial, we will learn LeetCode #435: Non-overlapping Intervals in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.
What Is the Non-overlapping Intervals Problem?
This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.
For this problem, we will use greedy sorting because it gives a clean and optimized solution.
Example input: intervals = [[1,3],[2,4],[4,6],[5,7]] Expected result: Output: 2 Explanation: Remove two intervals to stop overlaps.
Beginner-Friendly Idea
The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.
At each step, ask: “What do I already know, and how does the current value change my answer?”
Using our example: intervals = [[1,3],[2,4],[4,6],[5,7]] Approach: greedy sorting We update variables step by step until we reach: Output: 2
Why Do We Use This Approach?
A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.
That is why greedy sorting is useful for this problem.
Step-by-Step Explanation
Let us dry run the algorithm using a custom example.
Step 1 Use this custom example. intervals = [[1,3],[2,4],[4,6],[5,7]] We will solve it using greedy sorting. Step 2 Look at the first important value from the example and create the variables needed by the algorithm. current_state = based on the first value answer = not finished yet Step 3 Move to the next useful value and update the state. The algorithm compares the new value with the old state. If the new value improves the answer, we update the answer. Step 4 Continue this process until all useful values are processed. After processing the example, we get: Output: 2 Why? Remove two intervals to stop overlaps.
Important Code Logic
The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.
Think like this: old_state = what we knew before current_value = value we are checking now new_state = updated result after using current_value For our example, the final state gives: Output: 2
Example 1
Input: intervals = [[1,3],[2,4],[4,6],[5,7]] Output: Output: 2 Explanation: Remove two intervals to stop overlaps.
Example 2
Input: intervals = [[1,2],[2,5],[3,4],[6,8]] Output: 1 Explanation: Remove one interval to make the rest non-overlapping.
Python Code
Here is the complete Python solution for LeetCode #435.
class OverlappingIntervalRemover:
def erase_overlap_intervals(self, intervals):
intervals.sort(key=lambda item: item[1])
removed = 0
previous_end = float("-inf")
for start, end in intervals:
if start >= previous_end:
previous_end = end
else:
removed += 1
return removed
remover = OverlappingIntervalRemover()
print(remover.erase_overlap_intervals([[1, 4], [2, 3], [3, 5], [6, 8]])) # Output: 1
print(remover.erase_overlap_intervals([[1, 2], [2, 3], [3, 4]])) # Output: 0Java Code
Here is the complete Java solution for LeetCode #435.
import java.util.Arrays;
class OverlappingIntervalRemover {
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> a[1] - b[1]);
int removed = 0;
int previousEnd = Integer.MIN_VALUE;
for (int[] interval : intervals) {
int start = interval[0];
int end = interval[1];
if (start >= previousEnd) {
previousEnd = end;
} else {
removed++;
}
}
return removed;
}
public static void main(String[] args) {
OverlappingIntervalRemover remover = new OverlappingIntervalRemover();
System.out.println(remover.eraseOverlapIntervals(new int[][] {{1,4}, {2,3}, {3,5}, {6,8}})); // 1
System.out.println(remover.eraseOverlapIntervals(new int[][] {{1,2}, {2,3}, {3,4}})); // 0
}
}Time and Space Complexity
Time Complexity: O(n log n)
The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.
Space Complexity: O(n)
The extra space is used for the variables or data structures needed by the optimized approach.
Final Summary
LeetCode #435: Non-overlapping Intervals becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.