Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Example 1:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: Longest consecutive sequence is [1, 2, 3, 4].
Therefore its length is 4.
Example 2:
Input: [0, 2, 0, 1, 2, 3, 1]
Output: 4
Explanation: Longest consecutive sequence is [0, 1, 2, 3].
Therefore its length is 4.
Note that we count each value once, even tho values 0, 1 and 2 appear 2 times each in nums
Note:
Your algorithm should run in O(n) time and use O(n) extra space.
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Solution #2 · O(n)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check