↓Skip to main content
  1. LeetCode/

LeetCode 128: Longest Consecutive Sequence

·2 mins· ·
LeetCode Medium Array Hash-Table Union-Find
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-27

  • Submissions: Wrong Answer ×11 → Accepted ×3

Approach
#

The problem requires O(n), so no sorting. Put every value in a set (Hash Table); x starts a run only if x - 1 is absent, and then count upward x + 1, x + 2, .... Each value is a start at most once and counted at most once, O(n) in total. The set also removes duplicates.

My Attempts
#

This took 14 submissions, all “sort and find runs” versions (against the O(n) requirement):

  • At first the run formula and initial values were wrong: [7] returned 0.
  • After that the length was assigned as max_length = end - start + 1, so a later, shorter run overwrote an earlier, longer one: in [4, 5, 7, 8, 3, 0] the run 3, 4, 5 has length 3, but it returned 2.
  • Duplicates were not handled: [4, 3, 3] returned 3 instead of 2. A dup counter subtracting repeats plus taking the max passed.

Solution
#

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        s = set(nums)
        best = 0
        for x in s:
            if x - 1 not in s:
                y = x
                while y + 1 in s:
                    y += 1
                best = max(best, y - x + 1)
        return best

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Count only from starts, or counting from every value is O(n²).
  • Iterate over the set so duplicates count once.
  • Sorting is O(n log n), against the requirement; a sorted version must also handle duplicates and take the max rather than overwrite.

Interview Explanation
#

I put the numbers in a set; a value starts a run only when x - 1 is missing, and from each start I count upward until the run breaks, keeping the longest. Each value is touched at most twice, so time is O(n).

Related

LeetCode 347: Top K Frequent Elements
·1 min
LeetCode Medium Array Hash-Table Divide-and-Conquer Sorting
LeetCode 347 note: count first, then take the k most frequent with a size-k heap or a bucket sort indexed by count
LeetCode 73: Set Matrix Zeroes
·2 mins
LeetCode Medium Array Hash-Table Matrix
LeetCode 73 note: record which rows and columns contain a 0 first, then update afterward; the follow-up uses the first row and column as markers
LeetCode 49: Group Anagrams
·2 mins
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 note: use each string’s sorted form as a key; strings sharing a key form one anagram group
LeetCode 36: Valid Sudoku
·2 mins
LeetCode Medium Array Hash-Table Matrix
LeetCode 36 note: each digit may appear once per row, column and 3 × 3 box; put (digit, row), (digit, column) and (digit, box) keys into one set
LeetCode 167: Two Sum II - Input Array Is Sorted
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search
LeetCode 167 note: sorted, so move two pointers inward, shifting right when the sum is too large and left when too small; indices are 1-based
LeetCode 238: Product of Array Except Self
·2 mins
LeetCode Medium Array Prefix-Sum
LeetCode 238 note: each answer is the product of everything to the left times everything to the right; two passes, no division