DEV Community

codingpineapple
codingpineapple

Posted on

1

LeetCode 128. Longest Consecutive Sequence (javascript solution)

Description:

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.

Solution:

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)) {
          currNum++;
          currMax++;
        }
        // Update max
        max = Math.max(max, currMax);
    }

    return max;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
vanshsh profile image
Vansh Sharma β€’

Thanks man

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay