Longest Consecutive Sequence
Length of the longest run of consecutive numbers, in a single pass.
Problem
Given an unsorted array of numbers, return the length of the longest run of consecutive numbers. Your solution must look at each number only a constant number of times - roughly one pass, written O(n).
- The numbers must be consecutive: 1, 2, 3, 4.
- Their order in the array does not matter.
- Solve it in O(n) time.
Examples
Approach
- Put every number in a Set, which also removes duplicates.
- For each number, check whether num - 1 is in the set. If it is, this number is in the middle of a run, so skip it.
- If num - 1 is missing, num starts a run: count upward while num + 1, num + 2, ... are in the set.
- Keep the longest run you have seen. Each number gets counted at most once as part of a run, so the whole thing stays one pass.
Brute force: Sort first, then scan for runs. Simple, but sorting alone costs more than one pass, so it misses what the problem asks for.
Common mistakes
- Counting upward from every number, instead of only from the ones that start a run, makes you re-walk the same runs again and again.
- Iterate over the set, not the array, so duplicate values are not counted twice.
Step through it
Pick an input and play the algorithm step by step. The highlighted line in the code follows each step, and you can edit the code to experiment.
Solution
The same approach in JavaScript, Python, and Java. Each is a complete program that prints the examples above - JavaScript runs here, so edit it and try your own input.
JavaScript solution
Output
Run code to see output...
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...
AI
System Design
Backend
- GraphQL8 modules · 69 lessons planned
- Core Python13 modules · 75 lessons planned
- FastAPI5 sections · 20 lessons
- Node.js14 modules · 206 lessons planned
- Node.js Performance7 chapters · 36 topics
- Event Loop Lifecycle6 phases · 3 scenarios
- Docker & Containerization11 modules · 144 lessons planned
- AWS for Developers14 modules · 219 lessons planned
- CI/CD & DevOps Automation10 modules · 134 lessons planned