Longest Consecutive Sequence
Problem Statement
Section titled “Problem Statement”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.
Examples
Section titled “Examples”| Input | Output | Longest sequence |
|---|---|---|
[100,4,200,1,3,2] | 4 | [1,2,3,4] |
[0,3,7,2,5,8,4,6,0,1] | 9 | [0,1,2,3,4,5,6,7,8] |
Constraints
Section titled “Constraints”0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Real-World Applications
Section titled “Real-World Applications”Complexity Comparison
Section titled “Complexity Comparison”| Approach | Time | Space | Best When |
|---|---|---|---|
| Hash Set | O(n) | O(n) | Required by problem, optimal |
| Sort First | O(n log n) | O(1)* | Sorting allowed, simpler to implement |
Approach 1: Hash Set (Recommended)
Section titled “Approach 1: Hash Set (Recommended)”Put all numbers in a hash set. For each number n, only start counting if n-1 is not in the set — that means n is the beginning of a sequence. Then count n, n+1, n+2, ... as long as they’re in the set. Track the maximum streak found.
Despite the nested loop appearance this is O(n) total because each number is visited at most twice: once as a candidate start, and at most once as part of a sequence expansion.
Step-by-step Example
Section titled “Step-by-step Example”Input: [100,4,200,1,3,2]
Set = {100, 4, 200, 1, 3, 2}
| num | n-1 in set? | Action | Streak | Max |
|---|---|---|---|---|
| 100 | 99 ✗ | count: 100 → streak 1 | 1 | 1 |
| 4 | 3 ✓ | skip (not start) | — | 1 |
| 200 | 199 ✗ | count: 200 → streak 1 | 1 | 1 |
| 1 | 0 ✗ | count: 1,2,3,4 → streak 4 | 4 | 4 |
| 3 | 2 ✓ | skip | — | 4 |
| 2 | 1 ✓ | skip | — | 4 |
Animated walkthrough
Use Next or Autoplay to see how we build the set, identify sequence starts, and expand each sequence rightward.
Pseudocode
Section titled “Pseudocode”function longestConsecutive(nums): num_set = set(nums) best = 0 for n in num_set: if (n - 1) not in num_set: # start of sequence length = 1 while (n + length) in num_set: length += 1 best = max(best, length) return bestSolution Code
Section titled “Solution Code”from typing import List
def longest_consecutive(nums: List[int]) -> int: num_set = set(nums) best = 0 for n in num_set: if (n - 1) not in num_set: # start of a sequence length = 1 while (n + length) in num_set: length += 1 best = max(best, length) return best#include <unordered_set>#include <vector>using namespace std;
class Solution {public: int longestConsecutive(vector<int>& nums) { unordered_set<int> num_set(nums.begin(), nums.end()); int best = 0; for (int n : num_set) { if (!num_set.count(n - 1)) { // start of a sequence int length = 1; while (num_set.count(n + length)) { length++; } best = max(best, length); } } return best; }};import java.util.HashSet;import java.util.Set;
class Solution { public int longestConsecutive(int[] nums) { Set<Integer> numSet = new HashSet<>(); for (int n : nums) numSet.add(n); int best = 0; for (int n : numSet) { if (!numSet.contains(n - 1)) { // start of a sequence int length = 1; while (numSet.contains(n + length)) { length++; } best = Math.max(best, length); } } return best; }}function longestConsecutive(nums) { const numSet = new Set(nums); let best = 0; for (const n of numSet) { if (!numSet.has(n - 1)) { // start of a sequence let length = 1; while (numSet.has(n + length)) { length++; } best = Math.max(best, length); } } return best;}use std::collections::HashSet;
impl Solution { pub fn longest_consecutive(nums: Vec<i32>) -> i32 { let num_set: HashSet<i32> = nums.into_iter().collect(); let mut best = 0; for &n in &num_set { if !num_set.contains(&(n - 1)) { // start of a sequence let mut length = 1; while num_set.contains(&(n + length)) { length += 1; } best = best.max(length); } } best }}func longestConsecutive(nums []int) int { numSet := map[int]bool{} for _, n := range nums { numSet[n] = true } best := 0 for n := range numSet { if !numSet[n-1] { // start of a sequence length := 1 for numSet[n+length] { length++ } if length > best { best = length } } } return best}Approach 2: Sort First
Section titled “Approach 2: Sort First”Sort the array. Iterate through it, skipping duplicates. Reset the streak when a gap greater than 1 appears. Simple to implement but does not meet the O(n) requirement.
Step-by-step Example
Section titled “Step-by-step Example”Input: [100,4,200,1,3,2]
Sorted: [1, 2, 3, 4, 100, 200]
| i | nums[i] | nums[i-1] | Action | Streak | Max |
|---|---|---|---|---|---|
| 1 | 2 | 1 | consecutive | 2 | 2 |
| 2 | 3 | 2 | consecutive | 3 | 3 |
| 3 | 4 | 3 | consecutive | 4 | 4 |
| 4 | 100 | 4 | gap → reset | 1 | 4 |
| 5 | 200 | 100 | gap → reset | 1 | 4 |
Pseudocode
Section titled “Pseudocode”function longestConsecutive(nums): if not nums: return 0 nums.sort() best = 1; streak = 1 for i in 1..len(nums)-1: if nums[i] == nums[i-1]: continue # skip duplicate if nums[i] == nums[i-1] + 1: streak += 1 best = max(best, streak) else: streak = 1 return bestSolution Code
Section titled “Solution Code”from typing import List
def longest_consecutive(nums: List[int]) -> int: if not nums: return 0 nums.sort() best = 1 streak = 1 for i in range(1, len(nums)): if nums[i] == nums[i - 1]: continue # skip duplicate if nums[i] == nums[i - 1] + 1: streak += 1 best = max(best, streak) else: streak = 1 return best#include <algorithm>#include <vector>using namespace std;
class Solution {public: int longestConsecutive(vector<int>& nums) { if (nums.empty()) return 0; sort(nums.begin(), nums.end()); int best = 1, streak = 1; for (int i = 1; i < (int)nums.size(); i++) { if (nums[i] == nums[i - 1]) continue; // skip duplicate if (nums[i] == nums[i - 1] + 1) { streak++; best = max(best, streak); } else { streak = 1; } } return best; }};import java.util.Arrays;
class Solution { public int longestConsecutive(int[] nums) { if (nums.length == 0) return 0; Arrays.sort(nums); int best = 1, streak = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] == nums[i - 1]) continue; // skip duplicate if (nums[i] == nums[i - 1] + 1) { streak++; best = Math.max(best, streak); } else { streak = 1; } } return best; }}function longestConsecutive(nums) { if (nums.length === 0) return 0; nums.sort((a, b) => a - b); let best = 1, streak = 1; for (let i = 1; i < nums.length; i++) { if (nums[i] === nums[i - 1]) continue; // skip duplicate if (nums[i] === nums[i - 1] + 1) { streak++; best = Math.max(best, streak); } else { streak = 1; } } return best;}impl Solution { pub fn longest_consecutive(mut nums: Vec<i32>) -> i32 { if nums.is_empty() { return 0; } nums.sort_unstable(); let mut best = 1; let mut streak = 1; for i in 1..nums.len() { if nums[i] == nums[i - 1] { continue; // skip duplicate } if nums[i] == nums[i - 1] + 1 { streak += 1; best = best.max(streak); } else { streak = 1; } } best }}import "sort"
func longestConsecutive(nums []int) int { if len(nums) == 0 { return 0 } sort.Ints(nums) best, streak := 1, 1 for i := 1; i < len(nums); i++ { if nums[i] == nums[i-1] { continue // skip duplicate } if nums[i] == nums[i-1]+1 { streak++ if streak > best { best = streak } } else { streak = 1 } } return best}Approach 3: Space-Optimized Variant
Section titled “Approach 3: Space-Optimized Variant”A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.
Pseudocode
Section titled “Pseudocode”function approach3(): // Implementation approach goes hereSolution Code
Section titled “Solution Code”"""Solution for Longest Consecutive Sequence"""
def solve(): """Implementation for approach 3 of Longest Consecutive Sequence""" pass
if __name__ == "__main__": print("Solution ready")#include <bits/stdc++.h>using namespace std;
// Solution for Longest Consecutive Sequence// Approach 3: Implementation
int main() {{ // Main implementation goes here return 0;}}/** * Solution for Longest Consecutive Sequence * Approach 3 */public class LongestConsecutiveSequenceSpaceOptimized {{
public static void main(String[] args) {{ // Implementation goes here }}}}/** * Solution for Longest Consecutive Sequence * Approach 3 */
function solve() {{ // Implementation goes here}}
module.exports = solve;/// Solution for Longest Consecutive Sequence/// Approach 3
fn main() {{ println!("Solution implementation");}}package main
import "fmt"
// Solution for Longest Consecutive Sequence// Approach 3
func main() {{ fmt.Println("Solution implementation")}}