Problem 128

Abstract / Summary

Find the length of the longest sequence of consecutive integers in a given list of numbers.

Note

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

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())
18 lines | 475 bytes | submitted August 31, 2023 | GitHub   6% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 47% (7+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Union Find
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 5.5 | μ = 5.15 | σ = 1.90

Complexity Analysis

Time: linear
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 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++
58 links | 42 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Longest Consecutive Sequence - Solution | Hashmap and Heap | Data Structure and Algorithms in JAVA'
Pepcoding 15 mins
Longest Consecutive Sequence - Solution | Hashmap and Heap | Data Structure and Algorithms in JAVA
YouTube video 'Longest Consecutive Sequence (LeetCode 128) | Full solution quick and easy explanation | Interviews'
Nikhil Lohia 19 mins
Longest Consecutive Sequence (LeetCode 128) | Full solution quick and easy explanation | Interviews
YouTube video 'Longest Consecutive Sequence - Leetcode 128 - Hashmaps & Sets (Python)'
Greg Hogg 8 mins
Longest Consecutive Sequence - Leetcode 128 - Hashmaps & Sets (Python)
YouTube video 'Longest Consecutive Sequence | Leetcode 128 | Hashset'
Ayushi Sharma 13 mins
Longest Consecutive Sequence | Leetcode 128 | Hashset
YouTube video 'Amazon Interview Question - Longest Consecutive Sequence - LeetCode 128'
AlgoJS 6 mins
Amazon Interview Question - Longest Consecutive Sequence - LeetCode 128
YouTube video 'Longest Consecutive Sequence (leetcode 128) | Array,HashTable Solutions | srkcodes'
Srk Codes 15 mins
Longest Consecutive Sequence (leetcode 128) | Array,HashTable Solutions | srkcodes
YouTube video 'Leetcode 128. Longest Consecutive Sequence - union-find solution'
Code-Yao 16 mins
Leetcode 128. Longest Consecutive Sequence - union-find solution
YouTube video 'Longest Consecutive Sequence | Leetcode 128 | Live coding session'
Coding Decoded 8 mins
Longest Consecutive Sequence | Leetcode 128 | Live coding session
YouTube video '128. Longest Consecutive Sequence || NEETCODE 150'
TechWithSaumya 18 mins
128. Longest Consecutive Sequence || NEETCODE 150
YouTube video 'Daily Leetcode #826: Jul 05, 2022 - 128. Longest Consecutive Sequence'
Programming Live with Larry 8 mins
Daily Leetcode #826: Jul 05, 2022 - 128. Longest Consecutive Sequence
YouTube video 'Longest Consecutive Sequence | LeetCode 128 | Theory + Python code'
Sai Anish Malla 15 mins
Longest Consecutive Sequence | LeetCode 128 | Theory + Python code
YouTube video 'Leetcode Solution - 128 Longest Consecutive Sequence'
John Leonardo 7 mins
Leetcode Solution - 128 Longest Consecutive Sequence
YouTube video 'LeetCode 128. Longest Consecutive Sequence | Hard | Algorithm Explained | C++'
Cherry Coding [IIT-G] 9 mins
LeetCode 128. Longest Consecutive Sequence | Hard | Algorithm Explained | C++
YouTube video 'Leetcode 128 Longest Consecutive Sequence | Coding Decoded SDE Revision Sheet'
Coding Decoded 3 mins
Leetcode 128 Longest Consecutive Sequence | Coding Decoded SDE Revision Sheet
YouTube video 'Longest Consecutive Sequence | LeetCode 128 | Coders Camp'
Coders Camp 10 mins
Longest Consecutive Sequence | LeetCode 128 | Coders Camp
YouTube video 'Daily Leetcode #432: Jun 06, 2021 - 128. Longest Consecutive Sequence'
Programming Live with Larry 14 mins
Daily Leetcode #432: Jun 06, 2021 - 128. Longest Consecutive Sequence
YouTube video 'Leetcode 128 🔥 Longest Consecutive Sequence  | NeetCode 150 Sheet | Optimal Approach + Dry Run'
Study Placement 12 mins
Leetcode 128 🔥 Longest Consecutive Sequence | NeetCode 150 Sheet | Optimal Approach + Dry Run
YouTube video 'Longest Consecutive Sequence - LeetCode #128 - C++'
Sean Chuah 4 mins
Longest Consecutive Sequence - LeetCode #128 - C++
YouTube video 'Longest Consecutive Sequence - Leetcode 128 - O(n) JavaScript Solution'
Web Coder Abhishek 7 mins
Longest Consecutive Sequence - Leetcode 128 - O(n) JavaScript Solution
YouTube video 'LeetCode #128 (Longest Consecutive Sequence) using Python | Solving the NeetCode 150 | Episode 38'
CodeMeetsWorld 13 mins
LeetCode #128 (Longest Consecutive Sequence) using Python | Solving the NeetCode 150 | Episode 38
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

27 solutions   August 31, 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