Python 0056.py
class Solution:
def within(self, left, right, pos):
return left <= pos and pos <= right
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
longest = defaultdict(int)
for i in intervals:
left = i[0]
right = i[1]
longest[left] = max(longest[left], right)
again = True
while again:
start = sorted(longest.keys())
again = False
for a in range(len(start)):
for b in range(a+1, len(longest)):
left = start[a]
right = longest[left]
next = start[b]
if not self.within(left, right, next):
break
if longest[next] > right:
longest[left] = longest[next]
del longest[next]
b -= 1
again = True
if again:
break
result = []
for i in longest:
result.append([ i, longest[i] ])
return result
Difficulty
and has an acceptance rate of about 52% (8+ million submissions).
Typical patterns to solve this problem:
- Array
- 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 interval-merging problem by first collapsing intervals that share the same left endpoint into a single entry that records the farthest right endpoint seen for that start. It then repeatedly scans the ordered start points, merging any interval that is completely covered by the current one. The final dictionary is transformed back into a list of merged intervals.
Key Steps
Building the longest-right map
The algorithm begins by iterating over the input list of intervals. For each interval it extracts the left and right bounds and stores the maximum right bound observed for that left value in a dictionary. This step guarantees that for any given start point only the interval that extends farthest to the right is retained.
longest = defaultdict(int)
for i in intervals:
left = i[0]
right = i[1]
longest[left] = max(longest[left], right)
Repeated merging loop
A flag named again controls a while-loop that continues as long as a merge occurs during an iteration. At the start of each pass the keys of the dictionary are sorted, producing an ordered list of start points. The outer loop iterates over each start point a, while the inner loop looks ahead to subsequent start points b. For each pair the algorithm checks whether the later start point lies inside the current interval using the helper within. If it does, the later interval is either absorbed (if it extends farther) or simply removed. The inner loop breaks as soon as a start point falls outside the current interval, leveraging the sorted order to avoid unnecessary checks.
again = True
while again:
start = sorted(longest.keys())
again = False
for a in range(len(start)):
for b in range(a+1, len(longest)):
left = start[a]
right = longest[left]
next = start[b]
if not self.within(left, right, next):
break
if longest[next] > right:
longest[left] = longest[next]
del longest[next]
b -= 1
again = True
if again:
break
Converting the dictionary to the result list
After no further merges are possible, the dictionary entries are transformed into the required list format. Each key/value pair becomes a two-element list representing a merged interval.
result = []
for i in longest:
result.append([ i, longest[i] ])
return result
Edge Cases Handled
The code correctly processes intervals that share identical left endpoints by retaining only the one with the greatest right endpoint during the initial map construction. Intervals that are completely nested within another are eliminated in the merging phase because the inner start point is found to be within the outer interval, leading to its removal. When two intervals touch at a boundary (e.g., [1,3] and [3,5]) the within check treats the boundary as inclusive, so the second interval is considered inside the first and merged accordingly. Intervals presented in any order are accommodated because the algorithm sorts the start points before attempting merges, ensuring order-independent behavior.
Performance Optimizations
The use of a defaultdict eliminates the need for explicit existence checks when updating the maximum right endpoint for a given left value. By collapsing intervals with the same start early, the algorithm reduces the number of entries that must be examined in later passes. The sorted list of start points is recomputed only at the beginning of each outer while-iteration, and the inner loop leverages the sorted order to break early once a start point lies outside the current interval, preventing needless comparisons. The again flag allows the outer loop to terminate as soon as a full pass completes without any merges, avoiding redundant scans. Deleting merged entries from the dictionary in place reduces memory overhead and keeps the working set small as the algorithm progresses.
ELI5 - Simplified Explanation
Imagine you have a big pile of colorful ribbons on a table. Some ribbons overlap each other, making them look messy. This code is like a helper that organizes the ribbons so they look neat and tidy.
First, the helper looks at every ribbon and writes down where it starts and where it ends in a notebook. If it finds two different ribbons that start at the same spot, it keeps the one that stretches out the furthest.
Next, the helper starts a game of hide and seek with the ribbons. It looks through the notebook to see if any ribbons are touching or crossing over each other. When it finds a ribbon that lands inside another one, it squashes them together into one long ribbon. It keeps doing this over and over again, checking the notebook until every single ribbon is separate and clear.
Finally, the helper takes all those long, organized ribbons and lays them out in a neat row. Now everything is tidy and ready to be used.
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 | C# | Rust | JS | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 57: Insert Interval
- problem 252: Meeting Rooms
- problem 253: Meeting Rooms II
- problem 495: Teemo Attacking
- problem 616: Add Bold Tag in String
- problem 715: Range Module
- problem 763: Partition Labels
- problem 986: Interval List Intersections
- problem 2158: Amount of New Area Painted Each Day
- problem 2213: Longest Substring of One Repeating Character
- problem 2276: Count Integers in Intervals
- problem 2406: Divide Intervals Into Minimum Number of Groups
- problem 2446: Determine if Two Events Have Conflict
- problem 2580: Count Ways to Group Overlapping Ranges
- problem 2655: Find Maximal Uncovered Ranges
- problem 2848: Points That Intersect With Cars
- problem 3169: Count Days Without Meetings
Solved On The Same Day
- problem 195: Tenth Line
- problem 53: Maximum Subarray
- problem 78: Subsets
- problem 86: Partition List
- problem 89: Gray Code
- problem 90: Subsets II
- problem 98: Validate Binary Search Tree
- problem 179: Largest Number
- problem 456: 132 Pattern
- problem 473: Matchsticks to Square
- problem 542: 01 Matrix
- problem 916: Word Subsets
- problem 1930: Unique Length-3 Palindromic Subsequences
- problem 233: Number of Digit One
- problem 295: Find Median from Data Stream
- problem 315: Count of Smaller Numbers After Self
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