Longest Consecutive Sequence

Problem statement

nums is unsorted. Report the length of the longest streak of consecutive integers (values that form …, x, x+1, x+2, …). Aim for linear time.

Example:

Input:

[100, 4, 200, 1, 3, 2]

Expected output:

4

Why: 1, 2, 3, 4 is the longest consecutive run.

Practice on LeetCode: Longest Consecutive Sequence

Golang Solution

func longestConsecutive(nums []int) int {

    if len(nums) == 0 || len(nums) == 1 {
        return len(nums)
    }

    maxSoFar := 1
    hashMap := make(map[int]bool)

    for _, num := range nums {
        hashMap[num] = true
    }

    for key, _ := range hashMap {
        currVal := key

        if _, ok := hashMap[currVal-1]; ok {
            continue
        }

        tempMax := 0
        for {
            if _, ok := hashMap[currVal]; ok {
                tempMax += 1
                currVal = currVal + 1
            } else {
                break
            }
        }

        if tempMax > maxSoFar {
            maxSoFar = tempMax
        }
    }

    return maxSoFar

}