The Longest Consecutive Sequence interview question gives you an unsorted array of integers and asks you to find the length of the longest sequence of consecutive numbers. The catch? You must solve it in time complexity. For example, given [100, 4, 200, 1, 3, 2], the longest consecutive sequence is [1, 2, 3, 4], and its length is 4.
This is a classic Hash Table problem that frequently appears in interviews at top tech companies. It is brilliant for evaluating a candidate's understanding of algorithmic time complexity. The naive reaction is to sort the array and count, but sorting takes time. The interviewer wants to see if you can utilize constant-time data structure lookups to break through the sorting bottleneck.
This problem perfectly illustrates the Hash Set pattern. The trick is to dump all numbers into a Hash Set to achieve lookups. Then, you iterate through the set. To ensure you aren't doing redundant work, you only start counting a sequence if the current number is the start of a sequence—meaning current_number - 1 does NOT exist in the set. From there, you simply count upwards current_number + 1, + 2, etc., tracking the sequence length.
Let's use the array [100, 4, 200, 1, 3, 2].
{100, 4, 200, 1, 3, 2}.100. Is 99 in the set? No. It's a sequence starter. Count up: 101 isn't there. Length = 1.4. Is 3 in the set? Yes. So 4 is NOT a starter. Skip.200. Is 199 in the set? No. Starter. Length = 1.1. Is 0 in the set? No. Starter. Count up: 2 is there, 3 is there, 4 is there, 5 is not. Length = 4.3 and 2. Both have their predecessors (2 and 1) in the set, so we skip them.
The max length we found was 4.The number one mistake candidates make is sorting the array, which immediately fails the time complexity requirement. Even when candidates use a Hash Set, they often forget the crucial check (if !set.contains(num - 1)). Without this check, the algorithm will attempt to count sequences starting from the middle, degrading the performance back to in the worst-case scenario.
When preparing for the Longest Consecutive Sequence coding pattern, deeply internalize the "sequence starter" logic. In Hash Set problems, the key to efficiency is knowing what to skip. Asking "Is this the beginning of a chain?" prevents overlapping work and keeps your algorithms strictly linear.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Islands II | Hard | Solve | |
| Find All Duplicates in an Array | Medium | Solve | |
| Convert an Array Into a 2D Array With Conditions | Medium | Solve | |
| Brick Wall | Medium | Solve | |
| 4Sum II | Medium | Solve |