MEDIUM NC#9 Blind #31 Arrays & Hashing
128. Longest Consecutive Sequence
๐ 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.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Use set for O(1) lookups
- โ Only start counting from beginning of sequences
- โ A number is a sequence start if num-1 is not in set
- โ Time: O(n), Space: O(n)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse set for O(1) lookups
- โขOnly start counting from beginning of sequences
- โขA number is a sequence start if num-1 is not in set
Common Pitfalls
- โขTime: O(n), Space: O(n)
๐งช Test Cases
Hidden tests on submit: 2
Test Case 1
Not run Input:
longestConsecutive([100,4,200,1,3,2]); Expected:
4 Test Case 2
Not run Input:
longestConsecutive([0,3,7,2,5,8,4,6,0,1]); Expected:
9 Test Case 3
Not run Input:
longestConsecutive([9,1,4,7,3,-1,0,5,8,-1,6]); Expected:
7 ๐ Code Editor
๐ค Output