#128

Longest Consecutive Sequence

Medium
ArrayHash TableUnion-FindHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a HashSet to store the numbers, allowing for O(1) average time complexity for lookups. This way, we can efficiently find the start of each sequence and count its length without sorting.

⚙️

Algorithm

5 steps
  1. 1Step 1: Insert all numbers into a HashSet for O(1) access.
  2. 2Step 2: Initialize a variable to keep track of the longest sequence length.
  3. 3Step 3: Iterate through each number in the array. For each number, check if it is the start of a sequence (i.e., number - 1 is not in the set).
  4. 4Step 4: If it is the start, count the length of the sequence by checking for consecutive numbers in the set.
  5. 5Step 5: Update the longest sequence length if the current count is greater.
solution.py14 lines
1# Full working Python code
2
3def longest_consecutive(nums):
4    num_set = set(nums)
5    longest = 0
6    for num in num_set:
7        if num - 1 not in num_set:  # start of a sequence
8            current_num = num
9            current_streak = 1
10            while current_num + 1 in num_set:
11                current_num += 1
12                current_streak += 1
13            longest = max(longest, current_streak)
14    return longest

Complexity note: The time complexity is O(n) because we traverse the array and perform constant time operations with the HashSet. The space complexity is O(n) due to storing the numbers in the HashSet.

  • 1Using a HashSet allows for O(1) average time complexity for lookups, which is crucial for efficiently finding consecutive sequences.
  • 2Identifying the start of a sequence by checking if the previous number is absent helps avoid unnecessary checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.