Problem statement
Solution
The key insight needed to solve this problem is that a consecutive sequence will always
look like num, num + 1, num + 2, ..., num + X, where the first integer num is one of
the unique integers in the nums array and X + 1 is the length of this consecutive
sequence.
Hence, to find the length of the longest consecutive sequence in the nums array, we
determine what X + 1 is for each unique num in the nums array. We do so as follows:
- Because the
numsarray can contain duplicates, convert it into a hash set to determine its unique elements. Additionally, a hash set offers $O(1)$ look-up costs. Call the resulting hash setnums_unique. - Initialize a running variable
max_lengthto record the length of the longest consecutive sequence amongst all other consecutive sequences. - For each
numinnums_unique:
a. Ifnum - 1is innums_unique, then we will skip thisnumand move on to the next one. This is because ifnum - 1is innums_unique, thennumis part of a larger sequence, so counting fromnumonwards will always lead to a shorter sequence. Hence, we skip thisnumto avoid the extra iterations. For example, ifnums = [1,2,3,4,5], then without this condition, we would check the sequences(2,3,4,5),(3,4,5),(4,5),and(5)when we already know that(1,2,3,4,5)is the longest sequence.
b. Otherwise, initialize a variablelengthto1.
c. Keep incrementinglengthby1untilnum + lengthis not innums_unique.
d. Setmax_lengthtomax(max_length, length)to update it. - Return
max_length.
If $n$ is the length of the nums array, then this solution requires $O(n)$ time in the
worst case (because we iterate over the nums array once). This solution will also
require $O(n)$ space due to the hash set nums_unique.
Here is what this solution looks like in Python:
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums_unique = set(nums)
max_length = 0
for num in nums_unique:
if (num - 1) in nums_unique:
continue
length = 1
while (num + length) in nums_unique:
length += 1
max_length = max(length, max_length)
return max_length