Longest Consecutive Sequence
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 with input: nums = []
Example with input: nums = [0,3,7,2,5,8,4,6,0,1]
Example with input: nums = [100,4,200,1,3,2]
Algorithm Flow
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.
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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
