Date and Time: Sep 9, 2024, 15:52 (EST)
Link: https://leetcode.com/problems/longest-consecutive-sequence/
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.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
-
0 <= nums.length <= 10^5
-
-10^9 <= nums[i] <= 10^9
-
Convert
counts
into a set(), so we can avoid duplicate elements. -
We loop over
counts
instead ofnums
to avoid looping duplicate elements, then we first check if(i-1)
incounts()
or not, if not, that means this current element is the start of a sequence, then we use a while loop to find ifi + tmp
incounts()
, and we incrementtmp
until the current consecutive sequence is finished. We updateres = max(res, tmp)
.
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
# Use a set() to convert nums to avoid duplicate elements
# First find the smallest element by checking if (i-1) not in set
# Then add 1 to this element each time and check if the added element is in set(), and we can update res
# TC: O(n), n = len(nums), SC: O(n)
nums = set(nums)
res = 0
for n in nums:
if n - 1 not in nums:
tmp = 1
while n + tmp in nums:
tmp += 1
res = max(res, tmp)
return res
Time Complexity: n
is the length of nums
.
Space Complexity: