LeetCode Blog

Solutions for LeetCode problems - Written by ansidev

128. Longest Consecutive Sequence

Author's avatar
ansidev Posted on December 1, 2026

Problem

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:

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

Example 3:

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

Constraints:

Analysis

  1. The key requirement is an O(n) time algorithm, so sorting the array (O(n log n)) is not acceptable for the optimal solution.
  2. A consecutive sequence is a run x, x+1, x+2, ..., x+K-1. Only the smallest number x of a run needs to be considered as a starting point: if x-1 exists in the array, then x is not the beginning of a sequence, and its run will be discovered when we start from x-1 (or an even smaller number).
  3. Algorithm:
    • Put every number into a hash set so existence checks are O(1).
    • For each number n in the set, if n-1 is not in the set, then n starts a sequence. Count how far the run goes (n+1, n+2, …) and keep the maximum length.
  4. Each number can start at most one sequence, and the inner counting loop only visits numbers that belong to that sequence. Every number is therefore examined a constant number of times, giving O(n) time and O(n) space.

Example walkthrough with nums = [100, 4, 200, 1, 3, 2]:

Number nn-1 in set?ActionRun length
100NoStart from 100; 101 missing1
4Yes (3)Skip—
200NoStart from 200; 201 missing1
1NoStart from 1; run 1, 2, 3, 4; 5 missing4
3Yes (2)Skip—
2Yes (1)Skip—

The maximum run length is 4.

Edge cases:

Approaches

Approach 1

Approach

  1. Build a hash set containing all numbers in nums.
  2. Iterate over the set. For each number n:
    • If n-1 is in the set, skip n — it is not the start of a sequence.
    • Otherwise, count upward (n+1, n+2, …) while the numbers exist in the set, and update the longest length found.
  3. Return the longest length.

Solutions

func longestConsecutive(nums []int) int {
	numSet := make(map[int]bool, len(nums))
	for _, n := range nums {
		numSet[n] = true
	}

	longest := 0
	for n := range numSet {
		// Only start counting from the beginning of a sequence.
		if numSet[n-1] {
			continue
		}

		currentNum := n
		currentStreak := 1
		for numSet[currentNum+1] {
			currentNum++
			currentStreak++
		}

		if currentStreak > longest {
			longest = currentStreak
		}
	}

	return longest
}

Complexity

References