Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
nums = [100,4,200,1,3,2]4By storing all numbers in a HashSet, we get O(1) contains checks. We only start counting from a number that has no predecessor — this guarantees we never recount the same sequence from the middle. Even though there is a while loop inside the for loop, each number is touched at most twice total, keeping the overall complexity O(n).
Sorting first costs O(n log n). And counting up from every single number repeats the same work again and again.
Put every number in a hash set. Only start counting from a number that begins a run, meaning the number −1 is not in the set. Then count up while the next number exists.
Only count from the start of a run, where x −1 is missing. That keeps the whole thing linear.
Run the animation above on your own input, or watch the 1:23 video explanation of Longest Consecutive Sequence with a dry run and Java code.