Skip to content

Latest commit

 

History

History
64 lines (46 loc) · 2.86 KB

128.Longest_Consecutive_Sequence(Medium).md

File metadata and controls

64 lines (46 loc) · 2.86 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:

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: $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