π·οΈ Category: HashMap / Algorithms | π― Difficulty:
Easy| π₯ Frequency: β β β β β
π Problem Statement
Given a list of integers and a target, return the indices of two numbers that add up to target using the concept of Two Sum.
π₯ Input β nums = [2, 7, 11, 15], target = 9
π€ Output β [0, 1] # 2 + 7 = 9
π₯ Input β nums = [3, 2, 4], target = 6
π€ Output β [1, 2] # 2 + 4 = 6
π₯ Input β nums = [3, 3], target = 6
π€ Output β [0, 1]
π§ What the Interviewer is Testing
| Concept | Why It Matters |
|---|---|
| HashMap usage | Core data structure skill |
| O(n) thinking | Optimization over brute force |
| Complement logic | Mathematical reasoning |
β οΈ Warning: Never start with O(nΒ²) brute force. Go straight to the hashmap solution.
π‘ Approach
a + b = target β b = target - a (complement)
For every number, check if its complement already exists in the hashmap.
If yes β found the pair. If no β store current number and index.
β Optimal Solution
def two_sum(nums: list, target: int) -> list:
seen = {} # { number: index }
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
# ββ Test Cases βββββββββββββββββββββββββββββββββ
print(two_sum([2, 7, 11, 15], 9)) # β
[0, 1]
print(two_sum([3, 2, 4], 6)) # β
[1, 2]
print(two_sum([3, 3], 6)) # β
[0, 1]
π Step-by-Step Walkthrough
nums = [2, 7, 11, 15], target = 9:
| Step | i | num | complement | seen | Action |
|---|---|---|---|---|---|
| 1 | 0 | 2 | 7 | {} | Store 2β0 |
| 2 | 1 | 7 | 2 | {2:0} | β
Found! Return [0,1] |
π Complexity Analysis
ββββββββββββββββββββ¬βββββββββββββ¬βββββββββββββββββββββββββββ
β Approach β Time β Space β
ββββββββββββββββββββΌβββββββββββββΌβββββββββββββββββββββββββββ€
β Brute Force β O(nΒ²) β O(1) β
β HashMap β
β O(n) β O(n) β
ββββββββββββββββββββ΄βββββββββββββ΄βββββββββββββββββββββββββββ
π€ How to Explain in the Interview
βIβll use a hashmap. For each number I calculate its complement β target minus current number. If that complement already exists in the map, I return both indices. Otherwise I store the current number. This gives O(n) time at the cost of O(n) space.β
βIβll use a hashmap. For each number I calculate its complement β target minus current number. If that complement already exists in the map, I return both indices. Otherwise I store the current number. This gives O(n) time at the cost of O(n) space.β
π Common Follow-up Questions
Q1 β Multiple valid pairs?
results = []
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
results.append([seen[complement], i])
seen[num] = i
return results
Q2 β Numbers can be negative?
Same solution works β hashmap handles negatives fine.
π Set 1 of 4 β Python Interview Prep Series β devprepguide.com
