Problem
FAANG · LeetCode #128

Longest Consecutive Sequence — three-stage drill

1The ProblemMedium

Longest Consecutive Sequence

Length of the longest run of consecutive integers, in O(n).

length of the longest run of consecutive ints10042001321, 2, 3, 4 are all present (scattered) → run of length 4return4
Examples
[100,4,200,1,3,2]→ 4[0,3,7,2,5,8,4,6,0,1]→ 9

constraintUnsorted; must run in O(n) — so sorting is off the table.

2The PatternTIME O(n) · SPACE O(n)

Arrays & Hashing

Trade space for time: a hash map turns 'have I seen this?' into an O(1) lookup.

remember what you've seen in a hash map → O(1) lookup4021722344scan›value → countseen = {4: 1}
Problems using this pattern
3The SolutionRESULT → 4

Step through it

scan nums; the set answers “is x±1 here?” in O(1)nums1004200132x›100−1 not in set → START · run = 1↩ ANSWERbest so far =1set = {1004200132}
100 → is 99 in the set? no → a run starts here · count 100… → length 1
Step 1 / 7
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent