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.
0
.The key to solving this problem efficiently (in O(n)
time complexity) is to use a set for O(1)
average time complexity for checking the existence of elements.
Here’s the step-by-step strategy:
Convert the List to a Set: Converting the list to a set helps in O(1)
average time complexity for checking the presence of elements.
Iterate through the Set: For each element, check if it is the start of a sequence by verifying that the element minus one (num - 1
) is not in the set.
Count the Length of the Sequence: If an element is the start of a sequence, count the length of the sequence by checking how many consecutive numbers follow it.
Track the Maximum Length: Keep track of the maximum length of all found sequences.
def longestConsecutive(nums):
if not nums:
return 0
num_set = set(nums)
max_length = 0
for num in num_set:
# Only start counting if num is the start of a sequence
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
nums
.Thus, the overall time complexity is O(n)
. The space complexity is also O(n)
due to storing the elements in a set.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?