Skip to content
Home » Leetcode 128 Longest Consecutive Sequence

Leetcode 128 Longest Consecutive Sequence

Leetcode 128 Longest Consecutive Sequence

The key for the solution is the sort the nums array first before we loop through it. In each iteration, we need to check a couple of things:

  • Is the current number the same with the last one? If yes we skip to the next iteration
  • If the current number is not consecutive from the last number, we need update the value of the temp and result
  • At the end, we need to return the larger one between temp and result because the last iteration will not necessarily update the result value if it’s still consecutive.

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function(nums) {
    nums.sort((a, b) => a - b);
    let result = 0;
    let temp = 0;
    for(let i = 0; i < nums.length; i++) {
        if(nums[i] === nums[i - 1]) {
            continue
        }
        
        if(temp === 0 || nums[i] - nums[i - 1] === 1) {
            temp++
        } else {
            if(temp > result) {
                result = temp;
            }
            temp = 1
        }
    }

    return Math.max(temp, result)
};

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *