DSAHashingO(n) scan

Longest Consecutive Sequence Visualizer

What is Longest Consecutive Sequence

Numbers form a streak if they differ by 1, ignoring order and duplicates. Put every value in a set. Only start a streak from a number whose predecessor is missing — that is a true left edge. Then walk x+1, x+2, … while they exist.

  • Why the left-edge test: without it you would restart 3-4-5 from 4 and 5 and blow the O(n) budget.
  • Each number is visited a constant number of times across all walks.
  • Sorting also works but costs O(n log n). The set is the linear trick.

How this visualizer works

Array 100, 4, 200, 1, 3, 2. 1 has no predecessor, so the walk 1→2→3→4 yields length 4.

Interactive trace

hash_table.state

Input
Hash table
Current look-up
Match / window
Stored entry

current_action

Load an input, then press Play or Step.

live_trace.py

1def longestConsecutive(arr):
2s, best = set(arr), 0
3for x in s:
4if x-1 not in s:
5y, streak = x, 1
6while y+1 in s:
7y, streak = y+1, streak+1
8best = max(best, streak)
9return best

stdout — decision log

// each hash probe is recorded here
Speed Ready

Pseudocode & Complexity

idea.txt

1def longestConsecutive(arr):
2s, best = set(arr), 0
3for x in s:
4if x-1 not in s:
5y, streak = x, 1
6while y+1 in s:
7y, streak = y+1, streak+1
8best = max(best, streak)
9return best

complexity.md

OperationTime
Build setO(n)
Edge walks (total)O(n)
SpaceO(n)

Python implementation

solution.py

1def longestConsecutive(arr):
2 s, best = set(arr), 0
3 for x in s:
4 if x - 1 not in s:
5 y, streak = x, 1
6 while y + 1 in s:
7 y += 1
8 streak += 1
9 best = max(best, streak)
10 return best