Python 0128.py
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if not nums:
return 0
runs = {} # assume hashmap, access is O(1)
for n in nums:
runs[n] = 1
for n in nums:
first = n
length = 1
while first - 1 in runs:
first -= 1
runs[n] += runs[first]
del runs[first]
return max(runs.values())
Difficulty
and has an acceptance rate of about 47% (7+ million submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Union Find
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 defines a class Solution with a method longestConsecutive that receives a list of integers and returns the length of the longest sequence of consecutive numbers that can be formed from the elements of the list. The algorithm builds a hash-map (runs) that initially stores each distinct number with a placeholder value of 1. It then iterates through the original list, extending each number backward as far as possible while merging the lengths of adjacent runs. Finally, the method returns the maximum value stored in the map, which corresponds to the longest consecutive run.
Key Steps
The first logical block checks for an empty input and returns 0 immediately, handling the edge case where no numbers are present.
if not nums:
return 0
Next, a dictionary named runs is created. Each number from the input list is inserted as a key with an initial length of 1. This step ensures that duplicate values are collapsed because assigning the same key repeatedly overwrites the previous entry, leaving a single entry per distinct integer.
runs = {} # assume hashmap, access is O(1)
for n in nums:
runs[n] = 1
The core of the algorithm is a second pass over the input list. For each number n, the code attempts to locate a preceding integer (first - 1) that already exists in the map. If such a predecessor is found, the loop moves the first pointer one step backward, adds the length of the predecessor run to the current entry runs[n], and deletes the predecessor entry from the map. This process repeats until no further predecessor is present, effectively collapsing a chain of consecutive numbers into a single entry whose value represents the total length of that chain.
for n in nums:
first = n
length = 1
while first - 1 in runs:
first -= 1
runs[n] += runs[first]
del runs[first]
After all numbers have been processed, the dictionary contains only the lengths of distinct consecutive runs, each keyed by the highest number in its respective run. The final step extracts the maximum length from the dictionary values and returns it as the answer.
return max(runs.values())
Edge Cases Handled
The early return for an empty list guarantees that the function produces a sensible result (0) when there are no elements to evaluate. Because the dictionary stores each number only once, the algorithm naturally handles inputs containing duplicate values without additional logic; duplicates are ignored after the first insertion, preventing inflated run lengths. The while-loop condition first - 1 in runs ensures that the backward search stops precisely when the consecutive chain is broken, which correctly deals with isolated numbers and gaps in the sequence.
Performance Optimizations
The use of a hash-map (runs) provides constant-time average look-ups and deletions, allowing the algorithm to locate predecessors and update run lengths efficiently. By merging runs in place and deleting intermediate entries, the code reduces the number of active keys in the dictionary as it progresses, which limits memory usage to the number of distinct runs rather than the total number of elements. The two-pass structure-first populating the map, then consolidating runs-avoids repeated scanning of the same elements and ensures that each number participates in at most one backward traversal, leading to a streamlined execution path.
ELI5 - Simplified Explanation
Imagine you have a big bag of number blocks scattered all over the floor. You want to line them up to see how many you can put in a perfect sequence, like one, two, three, and so on.
First, you pick up every number block and put it into a special box that keeps things organized by what number is written on the block. Having that box makes it super easy to check if a specific number exists later.
Next, you go through each number block one by one. When you hold a number, you look in your box to see if the number right before it is hiding nearby. If it is, you grab that one too and join them together to make your group longer. You keep looking for the block that comes right before your current group until you cannot find any more numbers to add.
By doing this for every block, you eventually end up with several groups of connected numbers. Some groups might be just one block long, and others might be very tall towers. Finally, you look at all your groups and pick the one that has the most blocks stacked together, which tells you the length of the longest line you could build.
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 | 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++ | ||||||||||
| bujosa | Rust | ||||||||||
| 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 | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| lzl124631x | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | 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++ | ||||||||||
| bujosa | Rust | ||||||||||
| 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 | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| lzl124631x | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 298: Binary Tree Longest Consecutive Sequence
- problem 2177: Find Three Consecutive Integers That Sum to a Given Number
- problem 2274: Maximum Consecutive Floors Without Special Floors
- problem 2414: Length of the Longest Alphabetical Continuous Substring
- problem 3020: Find the Maximum Number of Elements in Subset
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
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