DEV Community 👩‍💻👨‍💻


Posted on

LeetCode 128. Longest Consecutive Sequence (javascript solution)


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.


Time Complexity : O(n)
Space Complexity: O(n)

var longestConsecutive = function(nums) {
    // Handle base case of empty array
    if (!nums.length) return 0;

    // Give ability to look up nums by value
    const set = new Set(nums);
    let max = 0;

    for (const num of set) {
        // Make sure we are starting at the beginning of the sequenece
        if (set.has(num - 1)) continue;

        let currNum = num;
        let currMax = 1;

        // Look numbers that make a consecutive sequence
        while (set.has(currNum + 1)) {
        // Update max
        max = Math.max(max, currMax);

    return max;
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

vanshsh profile image
Vansh Sharma

Thanks man

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post