LeetCode 128: Longest Consecutive Sequence is a Medium hashmap problem. This Python walkthrough develops a set sequence starts solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Hashmap |
| Reusable pattern | set sequence starts |
| Complexity | O(n) expected time and O(n) space |
Recognizing the pattern
A hash table converts a repeated search for prior information into an average constant-time lookup.
For this problem specifically, insert all values into a set and count forward only from values whose predecessor is absent. The invariant worth writing beside the code is: Every consecutive run is counted exactly once from its unique smallest value.
Step-by-step algorithm
- Identify the input state consumed by
longestConsecutive(nums)and initialize the data required by the set sequence starts pattern. - Insert all values into a set and count forward only from values whose predecessor is absent.
- After each update, verify the page’s central invariant: Every consecutive run is counted exactly once from its unique smallest value.
- Finish only after the boundary behavior is covered: Duplicates disappear in the set; negative and unsorted values behave normally.
Python solution
class Solution:
def longestConsecutive(self, nums):
values, best = set(nums), 0
for value in values:
if value - 1 not in values:
end = value
while end in values: end += 1
best = max(best, end - value)
return bestReading the implementation
The main entry point is longestConsecutive(nums). The named working state includes values, end, best; those variables make the set sequence starts state visible instead of hiding it in incidental control flow.
The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, insert all values into a set and count forward only from values whose predecessor is absent.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Insert all values into a set and count forward only from values whose predecessor is absent. Each update records the current item without invalidating earlier decisions; consequently, every consecutive run is counted exactly once from its unique smallest value.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n) expected time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Sorting may reduce implementation state and reveal ordering, but it can lose original positions and normally costs O(n log n). That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().longestConsecutive([100,4,200,1,3,2]) == 4Common mistakes and edge cases
- Problem-specific boundary: Duplicates disappear in the set; negative and unsorted values behave normally.
- Pattern-level pitfall: Choose whether to look up before inserting: inserting too early can accidentally match an element with itself.
- Invariant check: after every update, confirm that every consecutive run is counted exactly once from its unique smallest value.
Interview review checklist
- Explain why set sequence starts matches the structure of this input.
- State the invariant in one sentence before tracing code: Every consecutive run is counted exactly once from its unique smallest value.
- Derive O(n) expected time and O(n) space from how many times each element or state is visited.
- Test the boundary explicitly: Duplicates disappear in the set; negative and unsorted values behave normally.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 219. Contains Duplicate II · Next: 228. Summary Ranges