mediumArrays & HashingGoogleMetaAmazon
Marathon Bib Run
Runners drop their race bibs at the finish in random order. Find the length of the longest run of consecutive bib numbers.
Given an unsorted integer array `bibs`, return the length of the longest consecutive integer sequence. Must run in O(n) time.
Choose approach
100
04
1200
21
33
42
5Setset
100
4
200
1
3
2
1/8
Narrationstep 1 of 8
Dump every bib into a set for O(1) lookup. We only kick off counting from the SMALLEST number of a run (one with no predecessor present).
Variables
best=0
How to think about it
- Sorting gives O(n log n). We can do better.
- Put all numbers into a hash set for O(1) membership.
- For each candidate, don't count unless it is the start of a run (n − 1 absent).
- From a start, keep incrementing while n + len is in the set.
- Each number is visited at most twice total → O(n).
Edge cases to catch in interview
- Empty input → 0.
- Duplicates don't extend runs (set deduplicates).
- A single number is a run of length 1.
- Multiple runs — track the max.
Examples
Example 1
4{"bibs":[100,4,200,1,3,2],"values":[100,4,200,1,3,2]}
Run is 1→2→3→4.
Example 2
9{"bibs":[0,3,7,2,5,8,4,6,0,1],"values":[0,3,7,2,5,8,4,6,0,1]}
Run 0..8.
Example 3
3{"bibs":[1,0,1,2],"values":[1,0,1,2]}
Run 0→1→2 (duplicates don't help).
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed