128. Longest Consecutive Sequence

J.Gong

2026-12-04

0.91min

link

Given an unsorted integer array nums, return the length of the longest sequence of consecutive integers (elements do not need to be adjacent in nums).

Your algorithm must run in O(n) time.

Input: nums = [100,4,200,1,3,2]

Output: 4

Explanation: The longest consecutive sequence is [1, 2, 3, 4].

Input: nums = [0,3,7,2,5,8,4,6,0,1]

Output: 9

Input: nums = [1,0,1,2]

Output: 3

Constraints: 0 <= nums.length <= 10^5, -10^9 <= nums[i] <= 10^9.

This is not a hard problem. Just iterate over all the numbers (i), and count in a loop while i + 1 is also in the numbers. Record the best one.

An interesting thing is how Golang writes hash sets:

Go
func longestConsecutive(nums []int) int {
 seen := make(map[int]struct{}, len(nums))
 for _, x := range nums {
  seen[x] = struct{}{}
 }
 best := 0
 for x := range seen {
  if _, ok := seen[x-1]; ok {
   continue
  }
  y := x + 1
  for {
   if _, ok := seen[y]; !ok {
    break
   }
   y++
  }
  best = max(best, y-x)
 }
 return best
}

To make a hash map in Go, use map[K]V, and use make to build a slice, such as make([]int, 3).

Iterating over both uses range.

Here is a Go-specific syntax, the comma-ok idiom (if _, ok := seen[x-1]; ok): seen[x-1] is not a boolean, while the second return value is a boolean indicating existence.

if init; cond can also be used in other cases, like if n := len(a); n > 0.