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).
Code
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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Longest Consecutive Sequence Via Set?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.