Math Fundamentals18 sections · 814 units
Open in Course

Consecutive - Implementation

Smart iteration

Here is the solution:


function longestConsecutive(nums)
    numSet := convert nums to set
    maxLength := 0
    for each num in numSet
        if (num - 1) not in numSet then
            currentNum := num
            currentLength := 1
            while (currentNum + 1) in numSet
                currentNum := currentNum + 1
                currentLength := currentLength + 1
            maxLength := max(maxLength, currentLength)
    return maxLength

You only start counting from numbers that are sequence starts. Time: O(n)O(n), Space: O(n)O(n).