Two Sum Problem Classic Hash Solution in DSA Python - Time & Space Complexity
We want to understand how fast the classic hash-based solution for the Two Sum problem runs as the input size grows.
Specifically, how does the number of steps change when we have more numbers to check?
Analyze the time complexity of the following code snippet.
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
This code finds two numbers in the list that add up to the target using a hash map to check complements quickly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number once.
- How many times: Exactly once for each number in the list.
- Secondary operation: Checking if complement exists in the hash map (average constant time).
As the list gets longer, the code checks each number once and does a quick lookup for its complement.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and 10 lookups |
| 100 | About 100 checks and 100 lookups |
| 1000 | About 1000 checks and 1000 lookups |
Pattern observation: The number of steps grows roughly in a straight line with the input size.
Time Complexity: O(n)
This means the time to find the two numbers grows directly in proportion to how many numbers we have.
[X] Wrong: "Since there is a loop inside a loop, the time must be O(n²)."
[OK] Correct: The code only has one loop; the hash map lookup is very fast and does not add another full loop.
Understanding this solution's time complexity shows you can use data structures smartly to speed up problems, a key skill in interviews.
"What if we used a list instead of a hash map for lookups? How would the time complexity change?"
Practice
Two Sum Problem?Solution
Step 1: Understand the problem requirement
The Two Sum problem asks to find two numbers in an array that add up to a target value.Step 2: Explain the hash solution approach
Using a dictionary (hash map) allows storing each number's index and checking if the complement (target - current number) exists quickly.Final Answer:
Use a dictionary to store numbers and their indices for quick lookup -> Option AQuick Check:
Hash map lookup = fast pair finding [OK]
- Trying to sort the array which changes indices
- Using nested loops causing slow performance
- Not storing indices, only values
seen?Solution
Step 1: Recall Python dictionary membership syntax
In Python, to check if a key exists in a dictionary, use the syntaxif key in dict:.Step 2: Identify correct option
if key in seen: uses the correct syntax. if key exists in seen: and D are invalid syntax. if seen.has_key(key): is legacy and removed in Python 3.Final Answer:
if key in seen: -> Option BQuick Check:
Python dict key check = if key in dict [OK]
- Using outdated has_key() method
- Writing invalid syntax like 'exists in'
- Confusing keys with values
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
print(two_sum([2, 7, 11, 15], 9))Solution
Step 1: Trace the loop and dictionary updates
Iteration 0: num=2, complement=7, seen={}, complement not in seen, add 2:0.
Iteration 1: num=7, complement=2, complement 2 in seen at index 0, return [0,1].Step 2: Determine returned indices
The function returns indices [0,1] where nums[0]+nums[1]=2+7=9.Final Answer:
[0, 1] -> Option AQuick Check:
Indices of 2 and 7 = [0, 1] [OK]
- Returning values instead of indices
- Adding current number before checking complement
- Returning empty list incorrectly
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
if num in seen:
return [seen[num], i]
complement = target - num
seen[complement] = i
return []Solution
Step 1: Analyze dictionary key storage
The code stores complement as key with current index, but it should store the number as key to check complement later.Step 2: Identify impact of wrong key storage
Because complement is stored as key, the lookup for num in seen fails to find correct pairs, causing wrong or no results.Final Answer:
It stores complement as key instead of the number itself -> Option CQuick Check:
Store number as key, not complement [OK]
- Swapping complement and number keys
- Returning indices before checking complement
- Not using enumerate properly
nums = [3, 3, 4, 5] and target = 6, what will the classic hash solution return?Consider the code:
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
print(two_sum(nums, target))Solution
Step 1: Trace the loop with duplicates
Iteration 0: num=3, complement=3, seen={}, complement not in seen, add 3:0.
Iteration 1: num=3, complement=3, complement 3 in seen at index 0, return [0,1].Step 2: Understand duplicate handling
The solution correctly finds the two 3's at indices 0 and 1 that sum to 6.Final Answer:
[0, 1] -> Option DQuick Check:
Two 3's indices = [0, 1] [OK]
- Ignoring duplicates and returning empty list
- Returning wrong indices due to overwriting
- Assuming no pair exists when duplicates present
Ready to prove it?
Pass the test and this pattern moves unknown
