Understanding the Problem
We are given an unsorted array of integers, and our goal is to find the length of the longest sequence of consecutive numbers that can be formed from the array.
A consecutive sequence means numbers that follow one after another, like [3, 4, 5, 6]
. The order of elements in the input array doesn't matter, and we must only use unique numbers to form such sequences.
Step-by-Step Breakdown with Example
Example: [100, 4, 200, 1, 3, 2]
Let’s try to visualize the sequences hidden in this array:
- From
1
, we can find 2
, 3
, and 4
— a sequence of length 4.
- Other numbers like
100
and 200
are standalone.
So the longest consecutive chain is [1, 2, 3, 4]
, and the answer is 4
.
Exploring Edge Cases
Case 1: Fully Ordered Array
[1, 2, 3, 4, 5]
— Already a full sequence. We return 5
.
Case 2: With Duplicates
[5, 5, 5]
— We ignore duplicates. Only one unique number means a sequence length of 1
.
Case 3: Gapped Numbers
[10, 30, 50]
— No two numbers are consecutive. Each number stands alone, so the answer is 1
.
Case 4: Empty Array
[]
— No elements, hence no sequence. Return 0
.
Our Strategy to Solve It
We solve the problem efficiently by using a Set
to store all the unique numbers from the array. This helps in:
- Removing duplicates automatically
- Allowing O(1) lookups when checking for consecutive elements
For each number in the set, we check whether it could be the start of a new sequence — this is true if num - 1
does not exist in the set.
If it's a valid start, we then check for num + 1
, num + 2
, and so on, to count the length of that sequence. We track the maximum sequence length found during this process.
Each number is checked only once — either as a starting point or ignored if already part of a longer sequence. This means we never do redundant work.
Comments
Loading comments...