Problem 56

Abstract / Summary

Given a list of intervals, combine overlapping ones into a list of non overlapping intervals.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
39 lines | 1152 bytes | submitted August 17, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (8+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 3 | μ = 3.78 | σ = 1.66

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
58 links | 41 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Merge Intervals - Sorting - Leetcode 56'
NeetCode 11 mins
Merge Intervals - Sorting - Leetcode 56
YouTube video 'LeetCode 56. Merge Intervals (Algorithm Explained)'
Nick White 13 mins
LeetCode 56. Merge Intervals (Algorithm Explained)
YouTube video 'MERGE INTERVALS || LeetCode 56 || Hindi Solution'
Pepcoding 38 mins
MERGE INTERVALS || LeetCode 56 || Hindi Solution
YouTube video 'Merge Intervals - LeetCode 56 Python'
Deepti Talesra 8 mins
Merge Intervals - LeetCode 56 Python
YouTube video 'Merge Intervals - Leetcode 56 | by Sorting | Java & Python'
Code With K5KC 9 mins
Merge Intervals - Leetcode 56 | by Sorting | Java & Python
YouTube video 'Merge Intervals || Leetcode 56 || 1 Variant Question Big Tech Actually Asks'
Coding with Minmer 24 mins
Merge Intervals || Leetcode 56 || 1 Variant Question Big Tech Actually Asks
YouTube video 'Merge Intervals | Live Coding with Explanation | Leetcode #56'
Algorithms Made Easy 5 mins
Merge Intervals | Live Coding with Explanation | Leetcode #56
YouTube video 'Merge Intervals | LeetCode 56 | C++, Java, Python'
Knowledge Center 17 mins
Merge Intervals | LeetCode 56 | C++, Java, Python
YouTube video 'merge intervals | merge intervals leetcode | leetcode 56'
Naresh Gupta 9 mins
merge intervals | merge intervals leetcode | leetcode 56
YouTube video 'Merge Intervals | Leet code 56 | Theory explained + Python code'
Sai Anish Malla 9 mins
Merge Intervals | Leet code 56 | Theory explained + Python code
YouTube video 'MERGE INTERVALS | PYTHON | LEETCODE # 56'
Cracking FAANG 10 mins
MERGE INTERVALS | PYTHON | LEETCODE # 56
YouTube video 'Merge Intervals - LeetCode 56 - Coding Interview Questions'
One Code Man 4 mins
Merge Intervals - LeetCode 56 - Coding Interview Questions
YouTube video 'Merge Intervals - LeetCode 56 - JavaScript'
AlgoJS 9 mins
Merge Intervals - LeetCode 56 - JavaScript
YouTube video '21. Merge Intervals | Arrays - Hard | Learn DSA | Leetcode 56'
Ayushi Sharma 12 mins
21. Merge Intervals | Arrays - Hard | Learn DSA | Leetcode 56
YouTube video 'LeetCode 56. Merge Intervals Explanation and Solution EP4'
happygirlzt 7 mins
LeetCode 56. Merge Intervals Explanation and Solution EP4
YouTube video 'Facebook Coding Interview Question | Leetcode 56 | Merge Intervals'
WorkWithGoogler 14 mins
Facebook Coding Interview Question | Leetcode 56 | Merge Intervals
YouTube video 'leetCode 56 Merge Intervals | JSer - algorithm and JavaScript'
JSer 9 mins
leetCode 56 Merge Intervals | JSer - algorithm and JavaScript
YouTube video 'Leetcode 56: Merge Intervals in Telugu | Sorting + Merging Approach | Python DSA | SRKCodes'
Srk Codes 14 mins
Leetcode 56: Merge Intervals in Telugu | Sorting + Merging Approach | Python DSA | SRKCodes
YouTube video 'Leetcode 56 | Merge Intervals Using Stacks'
AppStuff 19 mins
Leetcode 56 | Merge Intervals Using Stacks
YouTube video 'Merge Intervals - 56. LeetCode - Java'
Teddy Smith 10 mins
Merge Intervals - 56. LeetCode - Java
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

17 similar problems

Solved On The Same Day

1 easy 12 medium 3 hard
17 solutions   August 17, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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