Python 0435.py
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
if len(intervals) <= 1:
return 0
# start => end
fromto = defaultdict(list)
for i in intervals:
start, end = i
fromto[start].append(end)
# reduce to at most one element starting at each point
unique = { }
result = 0
for f in fromto:
result += len(fromto[f]) - 1
unique[f] = min(fromto[f])
# from left to right
end = float("-inf")
for start in sorted(unique):
if start >= end:
end = unique[start]
else:
# collision
result += 1
# choose the shorter interval
end = min(end, unique[start])
return result
Difficulty
and has an acceptance rate of about 57% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Greedy
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of removing the minimum number of intervals so that the remaining intervals are non-overlapping. It follows a two-phase strategy: first it collapses intervals that share the same start point, then it scans the intervals in increasing order of start positions, deciding whether each interval can be kept or must be discarded. The function returns the total count of intervals that need to be removed.
Key Steps
The algorithm begins with a guard clause that handles trivial inputs.
if len(intervals) <= 1:
return 0
Next it groups intervals by their start coordinate using a defaultdict of lists.
fromto = defaultdict(list)
for i in intervals:
start, end = i
fromto[start].append(end)
The grouping phase is followed by a reduction step that keeps only the smallest end value for each distinct start point. While doing so it counts how many intervals are eliminated simply because they share the same start.
unique = {}
result = 0
for f in fromto:
result += len(fromto[f]) - 1
unique[f] = min(fromto[f])
The core of the solution is a left-to-right sweep over the sorted start points. An end variable tracks the end of the last interval that has been accepted. If the current start is not earlier than end, the interval is accepted and end is updated. Otherwise a collision is detected; the algorithm increments the removal counter and keeps the interval with the earlier finishing time.
end = float("-inf")
for start in sorted(unique):
if start >= end:
end = unique[start]
else:
result += 1
end = min(end, unique[start])
Finally the accumulated result value, representing the total number of intervals that must be erased, is returned.
return result
Edge Cases Handled
When the input list contains zero or one interval the early return ensures that no further processing occurs and the correct answer of zero removals is produced.
If multiple intervals begin at the same coordinate, the reduction loop counts all but the shortest interval as removals, guaranteeing that only one interval per start point proceeds to the sweep phase.
The sweep logic correctly deals with intervals that are nested or partially overlapping. By always retaining the interval with the smallest end time during a collision, the algorithm preserves the maximal room for subsequent intervals.
The initialization of end with negative infinity allows the first interval, regardless of its start value, to be accepted without special casing.
Performance Optimizations
The use of a defaultdict eliminates the need for explicit existence checks when appending end values, reducing overhead in the grouping stage.
Storing only the minimal end for each start point in the unique dictionary cuts down the number of elements that must be sorted and examined in the sweep, which can be significant when many intervals share the same start.
Sorting is performed only on the distinct start keys rather than on the full list of intervals, decreasing the size of the sorted collection.
The algorithm updates the end variable in place and avoids creating additional temporary lists during the sweep, keeping memory usage low and improving cache locality.
ELI5 - Simplified Explanation
Imagine you have a pile of colorful paper strips on the floor, and each one represents a time slot for playing with toys. Because you cannot play with two toys at the same time, you want to pick as many strips as possible without them bumping into each other.
The computer first organizes all these strips by looking at when they start. If many strips start at the exact same moment, the computer keeps the shortest one and sets the others aside because they are in the way. Keeping the shortest one makes it much easier to fit more strips later.
Next, the computer arranges all the remaining strips in a row from left to right, like lining up toys on a shelf. It starts with the very first strip and marks the time when it finishes. Then, the computer checks the next strip in line. If the new strip starts after the previous one finishes, that is great, and you can play with both. The computer updates the finishing time to the current strip's end.
If a strip tries to start before the previous one has finished, the strips are colliding. When a collision happens, the computer must remove one of them to keep everything tidy. It carefully compares the two strips and picks the one that ends sooner to throw away, which helps leave more room for the strips that follow. This process repeats for every single strip until all the overlaps are gone and the space is clear.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | Python | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | Python | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 2446: Determine if Two Events Have Conflict
Solved On The Same Day
- problem 521: Longest Uncommon Subsequence I
- problem 557: Reverse Words in a String III
- problem 697: Degree of an Array
- problem 771: Jewels and Stones
- problem 819: Most Common Word
- problem 1700: Number of Students Unable to Eat Lunch
- problem 2073: Time Needed to Buy Tickets
- problem 399: Evaluate Division
- problem 547: Number of Provinces
- problem 841: Keys and Rooms
- problem 1466: Reorder Routes to Make All Paths Lead to the City Zero
- problem 2462: Total Cost to Hire K Workers
- problem 2542: Maximum Subsequence Score
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality