The task
This task is taken from leetcodeLeetcode -
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.Your algorithm should run in \$O(n)\$ complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Input: [100, 4, 200, 1, 3, 2] Output: 4 /** Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. */
My solution
/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function(nums) {
const set = new Set(nums);
let longestStreak = 1;
let max = 0;
set.forEach(x => {
if (!set.has(x - 1)) {
let num = x;
while(set.has(++num)) { ++longestStreak; }
max = Math.max(max, longestStreak);
longestStreak = 1;
}
});
return max;
};
Time complexity is O(2n)\$O(2n)\$ which is still in the range of O(n)\$O(n)\$ time complexity.