Why does finding the longest consecutive sequence take O(n) time with a hash set despite nested while loops? | A1LabDavid to DSAEnglish • 17 hours ago

Why does finding the longest consecutive sequence take O(n) time with a hash set despite nested while loops?

message-square
0
1
Why does finding the longest consecutive sequence take O(n) time with a hash set despite nested while loops?
Why does finding the longest consecutive sequence take O(n) time with a hash set despite nested while loops? | A1LabDavid to DSAEnglish • 17 hours ago

Longest Consecutive Sequence: Why Nested Loops Run in $O(n)$ Time

The Longest Consecutive Sequence problem asks for the length of the longest run of consecutive integers (e.g., [100, 4, 200, 1, 3, 2] yields 4 for [1, 2, 3, 4]) in an unsorted array.

Sorting takes $O(n \log n)$ time. Inserting all numbers into an unordered hash set allows finding this sequence in $O(n)$ time, even though the standard algorithm contains a while loop nested directly inside a for loop.


The Crucial Condition: Sequence Head Filtering

A naive approach would check for consecutive successors (x + 1, x + 2, $\dots$) for every element in the set, triggering redundant traversals and degrading performance to $O(n^2)$.

The algorithm eliminates redundancy with a single line of logic: $$\text{Only start expanding if } (x - 1) \notin \text{hash_set}$$

  • If num - 1 is present in the set, num is in the middle or end of an existing sequence. We skip it entirely in $O(1)$ time.
  • If num - 1 is missing from the set, num is guaranteed to be the absolute start (head) of a brand-new consecutive sequence. Only then does the inner while loop execute.

Amortized Complexity Analysis (The Mathematical Proof)

Although the loops are syntactically nested, they do not perform multiplicative work:

  1. Outer Loop Work: The outer loop inspects each of the $n$ elements in the set once. For each element, it queries num - 1 in the hash set ($O(1)$ average time). Total outer loop overhead: $O(n)$.

  2. Inner while Loop Work:

    • The inner loop triggers only once per connected component (sequence).
    • Every number $y$ belonging to a sequence of length $L$ is visited by the while loop exactly once—specifically when the traversal started at the sequence’s root element ($y - L + 1$).
    • No number can belong to two distinct consecutive sequences because each integer has a unique successor ($y + 1$).

$$\text{Total inner loop steps across all iterations} = \sum_{\text{all sequences}} L_i \le n$$

Combining both parts: $$\text{Total Operations} = \underbrace{n \text{ set lookups}}{\text{Outer loop}} + \underbrace{\sum L_i \text{ lookups}}{\text{Inner loop across all heads}} \le n + n = 2n \implies O(n)$$


Visual Walkthrough: [100, 4, 200, 1, 3, 2]

  • Hash Set: {1, 2, 3, 4, 100, 200}
Number Is num - 1 in Set? Action Inner Loop Visits Running Max Length
100 Is 99 in set? $\rightarrow$ No Sequence Head. Expand sequence. Checks 101 (fails). Length = 1. 1
4 Is 3 in set? $\rightarrow$ Yes Skip immediately ($O(1)$). None (0) 1
200 Is 199 in set? $\rightarrow$ No Sequence Head. Expand sequence. Checks 201 (fails). Length = 1. 1
1 Is 0 in set? $\rightarrow$ No Sequence Head. Expand sequence. Visits 2, 3, 4, checks 5 (fails). Length = 4. 4
3 Is 2 in set? $\rightarrow$ Yes Skip immediately ($O(1)$). None (0) 4
2 Is 1 in set? $\rightarrow$ Yes Skip immediately ($O(1)$). None (0) 4
  • Across all elements, 1, 2, 3, and 4 were scanned exactly once inside the inner loop.

Implementation (C++ & Python)

C++ Implementation

#include <vector>
#include <unordered_set>
#include <algorithm>

int longestConsecutive(const std::vector<int>& nums) {
    // Populate hash set: O(n) average time and O(n) space
    std::unordered_set<int> num_set(nums.begin(), nums.end());
    int max_streak = 0;

    for (int num : num_set) {
        // Only evaluate if 'num' is the start of a consecutive sequence
        if (num_set.find(num - 1) == num_set.end()) {
            int current_num = num;
            int current_streak = 1;

            // Expand forward along the sequence
            while (num_set.find(current_num + 1) != num_set.end()) {
                current_num += 1;
                current_streak += 1;
            }

            max_streak = std::max(max_streak, current_streak);
        }
    }

    return max_streak;
}

Python Implementation

def longest_consecutive(nums: list[int]) -> int:
    num_set = set(nums)
    max_streak = 0

    for num in num_set:
        # Check if 'num' is the first number of a consecutive run
        if (num - 1) not in num_set:
            current_num = num
            current_streak = 1

            # Count upwards through consecutive members
            while (current_num + 1) in num_set:
                current_num += 1
                current_streak += 1

            max_streak = max(max_streak, current_streak)

    return max_streak

Complexity & Edge Cases

Metric Complexity Explanation
Time Complexity $O(n)$ average Inserting $n$ elements into the hash set takes $O(n)$ time. Each unique integer is checked at most twice (once in the outer loop, and at most once in the inner loop). Hash set lookups run in $O(1)$ amortized time.
Auxiliary Space $O(n)$ Required by the hash set to store unique elements.
  • Duplicates: Natural handling occurs because hash sets discard duplicate values, preventing redundant checks on identical numbers.
  • Hash Collisions Note: In worst-case scenarios with malicious inputs or poorly distributed custom hash functions, bucket collisions in unordered_set can degrade individual operations to $O(n)$, giving $O(n^2)$ worst-case. In practical runtime environments with randomized hashing, average time is strictly linear $O(n)$.