Longest Consecutive Sequence Via Set

Load numbers into a set and only count runs at their start (x-1 missing), so each element is visited at most twice and stays O(n).

GoData Integrity

Code

gosnippet
32 lines
package main

import "fmt"

// longestConsecutive: count runs only at sequence starts (x-1 missing),
// so every element is visited at most twice
func longestConsecutive(nums []int) int {
	set := make(map[int]bool, len(nums))
	for _, n := range nums {
		set[n] = true
	}
	best := 0
	for n := range set {
		if set[n-1] {
			continue // not a sequence start
		}
		length := 1
		for set[n+length] {
			length++
		}
		if length > best {
			best = length
		}
	}
	return best
}

func main() {
	fmt.Println(longestConsecutive([]int{100, 4, 200, 1, 3, 2}))
	fmt.Println(longestConsecutive([]int{0, 3, 7, 2, 5, 8, 4, 6, 1}))
	fmt.Println(longestConsecutive([]int{}))
}

Under the hood

All the action sits in the functions longestConsecutive and main — everything else is wiring.

Repetition is confined to for _, n := range nums — the rest of the file is straight-line.

Watch out for

  • No dependency list exists — the runtime already supplies everything used here.

Applying it

What you call into: func longestConsecutive(nums []int) int

Execute the file and main walks through longestConsecutive, in that order.

Statements that matter

for _, n := range nums {
	set[n] = true
}
for n := range set {
	if set[n-1] {
		continue // not a sequence start
	}
	length := 1
	for set[n+length] {
		length++
	}
	if length > best {
		best = length
	}
}
func main() {
	fmt.Println(longestConsecutive([]int{100, 4, 200, 1, 3, 2}))
	fmt.Println(longestConsecutive([]int{0, 3, 7, 2, 5, 8, 4, 6, 1}))
	fmt.Println(longestConsecutive([]int{}))
}

Interactive Tools for This Topic

FAQ

How do you run Longest Consecutive Sequence Via Set?
The runtime alone is enough: execute the file as a complete program.