Skip to content

Latest commit

 

History

History
68 lines (51 loc) · 3.14 KB

File metadata and controls

68 lines (51 loc) · 3.14 KB

128. Longest Consecutive Sequence (Medium)

Date and Time: Sep 9, 2024, 15:52 (EST)

Link: https://leetcode.com/problems/longest-consecutive-sequence/


Question:

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


Constraints:

  • 0 <= nums.length <= 10^5

  • -10^9 <= nums[i] <= 10^9


Walk-through:

  1. Convert counts into a set(), so we can avoid duplicate elements.

  2. We loop over counts instead of nums to avoid looping duplicate elements, then we first check if (i-1) in counts() or not, if not, that means this current element is the start of a sequence, then we use a while loop to find if i + tmp in counts(), and we increment tmp until the current consecutive sequence is finished. We update res = max(res, tmp).


Python Solution:

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 res

Time Complexity: $O(n)$, n is the length of nums.
Space Complexity: $O(n)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms