128. Longest Consecutive Sequence#
Difficulty: Medium
Link to Problem: To see the Longest Consecutive Sequence problem on LeetCode, click here!
Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n)
time.
Constraints:*
0 <=
nums.length
<= \(10^5\)\(-10^9\) <=
nums[i]
<= \(10^9\)
Solution:#
Here’s a Python function to solve this problem:
def longestConsecutive(nums):
if not nums:
return 0
num_set = set(nums)
max_length = 0
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_length = 1
while current_num + 1 in num_set:
current_num += 1
current_length += 1
max_length = max(max_length, current_length)
return max_length
Explanation:#
We start by defining the
longestConsecutive
function that takes thenums
array as input.We check if the
nums
array is empty. If it’s empty, there are no consecutive elements, so we return 0.We create a Python set called
num_set
and insert all elements from thenums
array into it. Using a set allows us to efficiently check for the existence of elements in O(1) time.We initialize a variable
max_length
to 0. This variable will keep track of the maximum length of consecutive elements sequence found.We iterate through the elements of the
num_set
. For each elementnum
, we check ifnum - 1
exists in thenum_set
. If it doesn’t exist, it meansnum
is the starting element of a potential consecutive sequence.Inside the loop, we initialize two variables:
current_num
to the current elementnum
andcurrent_length
to 1. We start with a length of 1 becausenum
itself is part of the sequence.We then enter a while loop that continues as long as
current_num + 1
exists in thenum_set
. This means we are incrementing the consecutive sequence.Inside the while loop, we increment
current_num
by 1 and also incrementcurrent_length
by 1 to account for the next consecutive element.We compare
current_length
with themax_length
and updatemax_length
if the current sequence is longer.After the while loop, we move to the next element in the outer loop and repeat the process.
Finally, we return the
max_length
as the result, which represents the length of the longest consecutive elements sequence in thenums
array.
The key idea here is to use a set to efficiently check for the existence of elements and to iterate through the elements, considering each element as the potential start of a consecutive sequence. By doing this, we can find the longest consecutive sequence in O(n) time complexity, where n is the number of elements in the array.
Test cases#
# Example 1:
nums1 = [100, 4, 200, 1, 3, 2]
print(longestConsecutive(nums1))
4
# Example 2:
nums2 = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
print(longestConsecutive(nums2))
9
Time and Space Complexity Analysis#
Let’s analyze the time and space complexity of the provided code:
Time Complexity:
The code is designed to run in O(n) time complexity, where n is the number of elements in the nums
array. Here’s the breakdown:
Constructing the
num_set
by inserting all elements fromnums
into it takes O(n) time because we perform an insertion operation for each element innums
.The main loop iterates through the elements in
num_set
. In the worst case, each element is visited only once, so the loop itself takes O(n) time.Within the loop, we have a while loop that may also take O(n) time in the worst case. However, this while loop is nested inside the main loop, so its overall time complexity remains O(n).
Therefore, the overall time complexity of the code is O(n).
Space Complexity:
The space complexity of the code is determined by the space used by the num_set
and a few additional variables. Here’s the breakdown:
num_set
is a set that stores the unique elements fromnums
. In the worst case, it can store all n elements fromnums
, so the space complexity is O(n).The additional variables used, such as
max_length
,current_num
, andcurrent_length
, have constant space requirements and do not depend on the size of the input array.
Therefore, the overall space complexity of the code is O(n) due to the space used by the num_set
.
Challenging Exercises:#
Write an algorithm that not only returns the length of the longest consecutive elements sequence but also returns the actual consecutive sequence itself.
Extend the problem to allow elements to be considered consecutive if they are within a certain absolute difference (e.g., less than or equal to k) instead of exactly 1. Write an algorithm that finds the longest such sequence and runs in O(n) time.