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).