Code Logo

Longest Consecutive Sequence

Published at26 Oct 2025
Array Manipulation Medium 7 views
Like12

This problem asks for the length of the longest run of numbers that can stand next to each other in counting order, like 1, 2, 3, 4. The numbers do not need to sit next to each other in the original list, but they do need to form a consecutive sequence of values.

That means you are looking for the largest block where every number is exactly one more than the number before it. Duplicate values do not make the streak longer, and missing numbers break the streak. The answer is only the length of the best sequence, not the sequence itself.

For example, in [100,4,200,1,3,2], the best consecutive run is 1,2,3,4, so the answer is 4. In [0,3,7,2,5,8,4,6,0,1], the run from 0 to 8 appears, so the answer is 9. If the list is empty, the answer is 0.

The important thing is to think about value order, not original position order.

Example Input & Output

Example 1
Input
nums = []
Output
0
Explanation

Example with input: nums = []

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

Example with input: nums = [0,3,7,2,5,8,4,6,0,1]

Example 3
Input
nums = [100,4,200,1,3,2]
Output
4
Explanation

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

Algorithm Flow

Recommendation Algorithm Flow for Longest Consecutive Sequence

Solution Approach

Find the longest consecutive sequence of numbers in an unsorted array. Use a hash set to store all numbers for O(1) lookups. Iterate through each number. If number - 1 is not in the set, this number starts a new sequence. Count consecutive numbers upward from this starting point and track the maximum streak length.

function longestConsecutive(nums) {
  var set = {}, maxLen = 0;
  for (var i = 0; i < nums.length; i++) set[nums[i]] = true;
  for (var i = 0; i < nums.length; i++) {
    if (!set[nums[i] - 1]) {
      var len = 1, cur = nums[i];
      while (set[cur + 1]) { len++; cur++; }
      if (len > maxLen) maxLen = len;
    }
  }
  return maxLen;
}

Only numbers that start a sequence (no predecessor in the set) are used as starting points. This avoids counting overlapping sequences and keeps the total work O(n).

Time complexity is O(n), space complexity is O(n).

Best Answers

java
import java.util.*;
class Solution {
    public int longest_consecutive(int[] nums) {
        if (nums.length == 0) return 0;
        Set<Integer> set = new HashSet<>();
        for (int x : nums) set.add(x);
        int maxLen = 0;
        for (int x : set) {
            if (!set.contains(x - 1)) {
                int current = x, streak = 1;
                while (set.contains(current + 1)) {
                    current++; streak++;
                }
                maxLen = Math.max(maxLen, streak);
            }
        }
        return maxLen;
    }
}