How to find the length of the longest consecutive sequence of an unsorted array of integers in JavaScript

1 Answer

0 votes
function longestConsecutive(nums) {
    const numSet = new Set(nums);
    let longestStreak = 0;

    for (const num of numSet) {
        // Check if it's the start of a sequence
        if (!numSet.has(num - 1)) {
            let currentNum = num;
            let currentStreak = 1;

            // Count consecutive numbers
            while (numSet.has(currentNum + 1)) {
                currentNum++;
                currentStreak++;
            }

            longestStreak = Math.max(longestStreak, currentStreak);
        }
    }

    return longestStreak;
}


const nums = [680, 4, 590, 3, 1, 2];

console.log(longestConsecutive(nums)); 




/*
run:

4

*/

 



answered Aug 19, 2025 by avibootz

Related questions

...