Code Logo

Longest Consecutive Sequence

Published atDate not available
Medium 0 views
Like0

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
Recommendation Algorithm Flow for Longest Consecutive Sequence

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;
    }
}