Longest Consecutive Sequence
Problem Statement
You are given an unsorted integer array nums.
Pick some of its values that form a run of consecutive integers — like 4, 5, 6, 7 — and return the length of the longest such run. The values can be anywhere in the array and in any order; only the values matter, not their positions.
Your algorithm must run in O(N) time.
An integer array nums (it can be empty and can contain duplicates).
The length of the longest run of consecutive values present in nums.
The values 1, 2, 3, 4 are all present. They are scattered in the array, but that does not matter.
The values 0 through 8 are all present. The second 0 does not make the run longer.
The run is 0, 1, 2.
- • 0 ≤ nums.length ≤ 10^5
- • −10^9 ≤ nums[i] ≤ 10^9
- • Must run in O(N) time.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
From each x, search the array for x + 1, x + 2, …
Sort; consecutive values become a stretch of the array
Count up from x only when x − 1 is not in the set
Treat every element x as a possible start. Search the whole array for x + 1; if found, search for x + 2, and so on. The longest chain found is the answer.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Arrays & Hashing translate into production architectures and low-level memory mechanics.