How to Explain Longest Consecutive Sequence in a Coding Interview (Step-by-Step)

How to Explain Longest Consecutive Sequence in a Coding Interview (Step-by-Step)

Longest Consecutive Sequence has a deceptively simple goal, but the optimal solution requires one non-obvious insight: only start counting from the beginning of a sequence. Miss that, and you’re writing O(n log n). Nail it, and you’ve got O(n).

In this post, you’ll learn exactly how to walk an interviewer through LeetCode 128 — from the brute-force pitfall to the HashSet approach, the sequence-start trick, and a clear complexity argument.


Problem Statement

LeetCode 128 Medium

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.

Examples

Example 1
Input: nums = [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive sequence is [1, 2, 3, 4].
Example 2
Input: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output: 9
Explanation: The longest consecutive sequence is [0, 1, 2, 3, 4, 5, 6, 7, 8].

Constraints

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109

What Is the Problem?

“I’m given an unsorted array of integers and I need to find the length of the longest run of consecutive integers — where consecutive means each number is exactly 1 more than the previous one. The order in the array doesn’t matter. I need to do this in O(n) time, which rules out sorting.”

Emphasising the O(n) constraint immediately is important — it signals to the interviewer that you’ve read the problem carefully and you know sorting is off the table.


Step 1: Compare Approaches Before Jumping to Code

✗ Rejected — O(n log n)
Sort the Array
Sort, then scan for consecutive runs. Simple, but O(n log n) — the problem explicitly forbids this time complexity.
✓ Optimal — O(n)
HashSet + Sequence Start
Load all numbers into a set for O(1) lookups. Only start counting from numbers that have no left neighbour. Achieves O(n) overall.
“Sorting gives O(n log n) which violates the constraint. The trick to hitting O(n) is using a HashSet — it gives us O(1) membership checks. Then we need one more insight to avoid redundant counting.”

The Key Insight — Only Start at Sequence Beginnings

💡 Core Insight

A number n is the start of a sequence if and only if n - 1 is not in the set. For every such start, count upward (n+1, n+2, …) while consecutive numbers exist. This guarantees each number is processed at most once across the entire loop — giving O(n) total.

“If I didn’t have this check, I’d restart a streak count from every element — so for the sequence [1,2,3,4], I’d count 4 streaks from 1, 3 from 2, 2 from 3, and 1 from 4. That’s O(n²) in the worst case. By skipping any number whose predecessor exists in the set, I only ever start a count from the true beginning of a sequence.”

Step 2: Explain the Algorithm in Plain English

1 Build a HashSet from the array

Convert nums into a set for O(1) lookups. Duplicates are automatically removed — this doesn’t affect correctness.

2 Iterate over every number in the set

For each number, check if num - 1 is in the set. If it is, skip — this number is not the start of a new sequence.

3 Count the streak upward

For sequence starters, count num + 1, num + 2, … as long as each is in the set. Track the streak length.

4 Update the global maximum

After each streak, update a running longest variable. Return it at the end.


Sequence Visualised — nums = [100, 4, 200, 1, 3, 2]

Here’s what happens when we scan the set. Numbers with no left neighbour in the set become sequence starters (blue); numbers that extend a streak are highlighted; those skipped because their predecessor exists are dimmed.

Set contents
1
2
3
4
100
200
num = 1
1
2
3
4
← streak = 4 ✓
num = 2
2
← 1 exists in set, skip
num = 3
3
← 2 exists in set, skip
num = 4
4
← 3 exists in set, skip
num = 100
100
← streak = 1
num = 200
200
← streak = 1
Sequence start (num−1 not in set)
Streak continuation
Skipped (not a start)

Result: the maximum streak seen is 4, from the sequence [1, 2, 3, 4].


Step 3: Talk Through the Code

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        num_set = set(nums)   # O(n) build — O(1) lookups from here on
        longest = 0

        for num in num_set:
            # Only start counting if this is the beginning of a sequence.
            # A number is a start if its left neighbour does NOT exist.
            if num - 1 not in num_set:
                current = num
                streak  = 1

                # Walk upward while consecutive numbers exist
                while current + 1 in num_set:
                    current += 1
                    streak  += 1

                longest = max(longest, streak)

        return longest

Point out that we iterate over num_set, not nums. This means duplicates are never visited twice. The inner while loop looks expensive, but across the entire outer loop each number is entered as current at most once — so the total number of while iterations across all outer iterations is at most n, giving O(n) overall.


Step 4: Highlight Edge Cases

1 Empty array
“If nums is empty, the set is empty, the loop never runs, and we return longest = 0 — correct.”
2 All duplicates
“If the input is [7, 7, 7], the set contains just {7}. We check if 6 is in the set (it isn’t), so 7 is a sequence start. The while loop checks 8 — also not in the set. Streak is 1. That’s correct.”
3 Single element
“A single-element array always returns 1 — the element itself forms a sequence of length one. Our code handles this correctly without any special casing.”
4 Negative numbers
“Negative integers work identically. If nums = [-3, -2, -1, 0], then -3 has no left neighbour -4 in the set, so it starts a streak of 4. The logic is sign-agnostic.”
5 Multiple disjoint sequences
“If there are several independent runs — say [1,2,3] and [10,11,12,13] — each is counted separately from its own start. The global max picks the longer one. No interaction between disjoint sequences.”

Step 5: State Time and Space Complexity

DimensionComplexityReason
Time O(n) Each number is visited by the outer loop once, and entered by the inner while loop at most once — total work is O(n)
Space O(n) The HashSet stores at most n distinct elements
“The inner while loop looks like it could make this O(n²), but it can’t. Each element is consumed by the while loop at most once across all outer iterations. Think of it as amortised — the total number of while steps summed across all outer iterations is bounded by n. So the overall time complexity is O(n).”

Interview Checklist for Longest Consecutive Sequence

  • Restate — “find the longest run of consecutive integers; order in the array doesn’t matter”
  • Call out the O(n) constraint immediately — explain why sorting is ruled out
  • Propose the HashSet approach and explain why it enables O(1) lookups
  • State the key insight — only start counting from numbers with no left neighbour in the set
  • Explain why skipping non-starts prevents O(n²) inner loop behaviour
  • Iterate over the set, not the array — avoid revisiting duplicates
  • Call out edge cases — empty input, all duplicates, negatives, disjoint sequences
  • Justify O(n) time amortised — each element enters the while loop at most once
  • State O(n) space for the HashSet
  • Ask clarifying questions before coding — can numbers be negative? can there be duplicates?

If you can solve Longest Consecutive Sequence cleanly, try these next:

💡 The amortised O(n) argument is the part most candidates fumble when asked “but isn’t that inner while loop O(n)?” Practice explaining it out loud: “each element enters the while loop at most once total, so the combined cost across all outer iterations is O(n).”
Scroll to Top