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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit