The goal is to find the longest chain of consecutive numbers that appear in the array, even though the array itself might be completely unsorted.
A consecutive sequence means a series of numbers like [3, 4, 5, 6]
— where each number is 1 more than the previous one. We are not concerned with the order of elements in the original array, just whether the numbers exist to form a sequence.
Understanding the Problem Through Cases
Case 1: Normal case with random numbers
In an array like [100, 4, 200, 1, 3, 2]
, even though the numbers are jumbled, there's a consecutive sequence [1, 2, 3, 4]
. We return 4, the length of that sequence.
Case 2: All numbers already in order
If the array is like [1, 2, 3, 4, 5]
, then the whole array forms one big sequence. We return the array’s length.
Case 3: Duplicates in the array
For arrays like [5, 5, 5]
, duplicates don’t help us. We only care about unique numbers. So, we ignore repeats and count the length of the sequence among distinct values.
Case 4: Disconnected numbers
If the numbers have big gaps between them like [10, 30, 50]
, then each number is its own sequence. The answer will be 1.
Case 5: Empty array
If no numbers are given, then there’s no sequence. So the answer is simply 0
.
How We Efficiently Solve It
We put all numbers into a HashSet
to remove duplicates and allow fast lookups. Then for each number, we check whether it could be the start of a new sequence (i.e., num - 1
is not in the set). If it is a valid start, we keep checking num + 1, num + 2, ...
to count how long the sequence continues.
This way, we avoid re-checking numbers that are part of earlier sequences and ensure we process each number only once. The result is a very fast and scalable solution that works even for large arrays.
⏱️ Time Complexity
Since we use a set and visit each number once, the time complexity is O(n), where n
is the number of elements in the array.