LeetCode 1: Two Sum is an Easy hashmap problem. This Python walkthrough develops a complement lookup 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 | Easy |
|---|---|
| Topic | Hashmap |
| Reusable pattern | complement lookup |
| Complexity | O(n) 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, for each value, check whether its required complement was seen earlier, then record the current index. The invariant worth writing beside the code is: The map contains one usable prior index for each processed value.
Step-by-step algorithm
- Identify the input state consumed by
twoSum(nums, target)and initialize the data required by the complement lookup pattern. - For each value, check whether its required complement was seen earlier, then record the current index.
- After each update, verify the page’s central invariant: The map contains one usable prior index for each processed value.
- Finish only after the boundary behavior is covered: Duplicate values can form the answer when the target is twice that value.
Python solution
class Solution:
def twoSum(self, nums, target):
seen = {}
for i, value in enumerate(nums):
if target - value in seen: return [seen[target - value], i]
seen[value] = iReading the implementation
The main entry point is twoSum(nums, target). The named working state includes seen; those variables make the complement lookup state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, for each value, check whether its required complement was seen earlier, then record the current index.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. For each value, check whether its required complement was seen earlier, then record the current index. Each update records the current item without invalidating earlier decisions; consequently, the map contains one usable prior index for each processed 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) 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().twoSum([2,7,11,15],9) == [0,1]Common mistakes and edge cases
- Problem-specific boundary: Duplicate values can form the answer when the target is twice that value.
- 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 the map contains one usable prior index for each processed value.
Interview review checklist
- Explain why complement lookup matches the structure of this input.
- State the invariant in one sentence before tracing code: The map contains one usable prior index for each processed value.
- Derive O(n) time and O(n) space from how many times each element or state is visited.
- Test the boundary explicitly: Duplicate values can form the answer when the target is twice that value.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 49. Group Anagrams · Next: 202. Happy Number