--- id: 128 title: Longest Consecutive Sequence difficulty: Medium tags: - array - hash-table - union-find status: Solved date_solved: 2026-06-05 leetcode_url: https://leetcode.com/problems/longest-consecutive-sequence/ review_needed: false --- # 128. Longest Consecutive Sequence > [!info] **Problem Link**: [LeetCode - Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) ## 📝 Problem Description 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` --- ## 💡 Approaches & Explanations ### Approach 1: Hash Set — *Optimal* To achieve $O(n)$ time complexity, we use a hash set for $O(1)$ lookups. The core idea is to identify the start of each possible sequence. A number `n` is the start of a sequence if `n - 1` is not present in the set. 1. Insert all numbers from `nums` into a hash set. 2. Iterate through each number `n` in the set: - Check if `n - 1` is in the set. - If `n - 1` is NOT in the set, `n` is the start of a sequence. - From `n`, keep checking for `n + 1`, `n + 2`, ... and increment the current sequence length. - Update the maximum length found so far. #### 📊 Complexity Analysis - **Time Complexity:** $O(N)$ where $N$ is the number of elements. Although there is a nested while loop, each element is visited at most twice (once by the main loop and once by the while loop), resulting in linear time. - **Space Complexity:** $O(N)$ to store the elements in the hash set. --- ## 💻 Code Implementations ### Python3 ```python class Solution: def longestConsecutive(self, nums: List[int]) -> int: num_set = set(nums) longest = 0 for n in num_set: # Check if n is the start of a sequence if (n - 1) not in num_set: length = 1 while (n + length) in num_set: length += 1 longest = max(length, longest) return longest ``` --- ## 🧠 Key Takeaways & Lessons - **Identifying Sequence Starts:** By checking for the absence of `n - 1`, we ensure that we only start counting from the beginning of a sequence, avoiding redundant work. - **Hash Set for Efficiency:** Trading space for time by using a Hash Set allows us to reduce what would be an $O(n^2)$ or $O(n \log n)$ problem into $O(n)$.