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
countsinto a set(), so we can avoid duplicate elements. -
We loop over
countsinstead ofnumsto 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 + tmpincounts(), and we incrementtmpuntil the current consecutive sequence is finished. We updateres = max(res, tmp).
Jun 1, 2026
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
# Q: Find the longest consecutive sequence from nums
# S: 1. Convert nums to set(nums) to support O(1) lookup
# 2. Loop over nums and check if n-1 not in nums to make sure we don't check repeatedly
# 3. Otherwise, we keep increasing cnt, so in the worst scenrio, we have LCS from the first index to the end, we use while loop for O(n) time, when we check other n in nums, we will skip the while loop.
# TC: O(n), n=len(nums), SC: O(n)
nums = set(nums)
res = 0
# Checking LCS
for n in nums:
cnt = 1
# Check if we have included before in other LCS
if n-1 not in nums:
while n+1 in nums:
cnt += 1
n += 1
res = max(res, cnt)
return resTime Complexity: n is the length of nums.
Space Complexity: