#435
Non-overlapping Intervals
MediumArrayDynamic ProgrammingGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal solution uses a greedy approach by sorting the intervals based on their end times. By always selecting the interval that ends the earliest, we can maximize the number of non-overlapping intervals.
⚙️
Algorithm
4 steps- 1Step 1: Sort the intervals by their end times.
- 2Step 2: Initialize a variable to keep track of the end time of the last added interval.
- 3Step 3: Iterate through the sorted intervals and count how many intervals overlap with the last added interval.
- 4Step 4: The number of intervals to remove is the total number of intervals minus the count of non-overlapping intervals.
solution.py14 lines
1# Full working Python code
2
3def eraseOverlapIntervals(intervals):
4 if not intervals:
5 return 0
6 intervals.sort(key=lambda x: x[1])
7 count = 0
8 end = intervals[0][1]
9 for i in range(1, len(intervals)):
10 if intervals[i][0] < end:
11 count += 1
12 else:
13 end = intervals[i][1]
14 return countℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(1) since we only use a few extra variables.
- 1Sorting the intervals by their end times allows us to efficiently determine overlaps.
- 2Greedy algorithms often provide optimal solutions for interval scheduling problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.