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 — no sorting allowed!
nums = [100, 4, 200, 1, 3, 2]
# Output: 4
# The longest consecutive sequence is [1, 2, 3, 4]
Key insight: Convert to a set for O(1) lookups. A number is the start of a sequence only if num - 1 is NOT in the set.
📋 Instructions
Implement `longest_consecutive(nums)` that returns the length of the longest consecutive sequence.
Test with `nums = [100, 4, 200, 1, 3, 2]` and print the result.
Convert nums to a set. For each num where (num-1) is NOT in the set (it's a sequence start), count how many consecutive numbers exist by checking num+1, num+2, etc. Track the maximum length.