Data Structures19 sections · 729 units
Open in Course

Longest Consecutive - Implementation

Complete solution

Here's the solution:

function longestConsecutive(nums)
    numSet := set of all elements in nums
    maxLength := 0

    for each num in numSet
        // Only start from sequence beginnings
        if (num - 1) not in numSet
            currentNum := num
            currentLength := 1

            // Count consecutive numbers
            while (currentNum + 1) in numSet
                currentNum := currentNum + 1
                currentLength := currentLength + 1

            maxLength := max(maxLength, currentLength)

    return maxLength

Time: O(n)O(n). Space: O(n)O(n).