25. Longest Consecutive Sequence
mediumAsked at SquareFind the longest unbroken streak of daily transaction IDs in a batch — Square's reconciliation team uses this hash-set scan to detect gaps in sequential invoice numbering that indicate missing or voided payments without sorting the full ledger.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Examples
Example 1
nums = [100,4,200,1,3,2]4Explanation: The longest consecutive sequence is [1,2,3,4], length 4.
Example 2
nums = [0,3,7,2,5,8,4,6,0,1]9Approaches
1. Sort and scan
Sort the array, then scan for consecutive integers, skipping duplicates. O(n log n) — violates the O(n) requirement.
- Time
- O(n log n)
- Space
- O(1)
function longestConsecutive(nums) {
if (!nums.length) return 0;
nums.sort((a, b) => a - b);
let best = 1, cur = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] === nums[i - 1]) continue;
if (nums[i] === nums[i - 1] + 1) { cur++; best = Math.max(best, cur); }
else cur = 1;
}
return best;
}Tradeoff:
2. Hash set — start-of-streak detection
Insert all values into a Set. For each value, only begin counting if value-1 is NOT in the set (it is a streak start). Walk forward until the chain breaks. Each number is visited at most twice — O(n).
- Time
- O(n)
- Space
- O(n)
function longestConsecutive(nums) {
const set = new Set(nums);
let best = 0;
for (const n of set) {
if (!set.has(n - 1)) { // n is the start of a streak
let len = 1;
while (set.has(n + len)) len++;
best = Math.max(best, len);
}
}
return best;
}Tradeoff:
Square-specific tips
The key insight Square tests is the start-of-streak guard: 'only begin counting from n if n-1 is absent.' Without it you count every number as a start and the algorithm is still technically O(n) amortized but the code is harder to reason about. State the guard first, before writing a single line. Square interviewers remember candidates who narrate the algorithm clearly — it maps directly to how they write design docs.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Longest Consecutive Sequence and other Square interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →