Longest Consecutive Sequence
MediumNeetCode 150Top Interview 150 Arrays & HashingWissen TechnologyPaytmOktaProblem
You get an unsorted array of integers nums. A consecutive run is a set of values
that follow each other with no gaps, like 4, 5, 6, 7. The values may appear anywhere in the array and in
any order.
Return the length of the longest consecutive run you can find in nums.
Constraints
- 0 ≤ nums.length ≤ 100000
- -1000000000 ≤ nums[i] ≤ 1000000000
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(n)
Time: Each value is walked over at most once: only the first value of a run starts a walk, and the walk covers exactly that run.
Space: The set stores every distinct value.
Put all values in a set. A value is the start of a run when value minus 1 is missing. Only from those starts, walk forward while the next value is present and remember the longest walk.