šÆ Two Sum
š¢ BeginnerHash Map Pattern
š Problem Statement
Given an array of integers nums and an integer target, return indices of the two numbers that add up to target. Assume exactly one solution exists and you may not use the same element twice.
Example: nums = [2,7,11,15], target = 9 ā Output: [0,1] (2 + 7 = 9)
š“ Approach 1: Brute Force - O(n²)
function twoSumBrute(array $nums, int $target): array {
$n = count($nums);
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
if ($nums[$i] + $nums[$j] === $target) {
return [$i, $j];
}
}
}
return []; // No solution (shouldn't happen per problem)
}
// Time: O(n²), Space: O(1)
š¢ Approach 2: Hash Map - O(n) ā Optimal
function twoSum(array $nums, int $target): array {
$seen = []; // value ā index
foreach ($nums as $i => $num) {
$complement = $target - $num;
// Check if we've seen the complement
if (isset($seen[$complement])) {
return [$seen[$complement], $i];
}
// Store current number's index
$seen[$num] = $i;
}
return [];
}
// Test
$result = twoSum([2, 7, 11, 15], 9);
print_r($result); // [0, 1]
š Dry Run
nums = [2, 7, 11, 15], target = 9
| Step | i | num | complement | seen map | Action |
|---|---|---|---|---|---|
| 1 | 0 | 2 | 7 | {}ā{2:0} | 7 not in seen, store 2ā0 |
| 2 | 1 | 7 | 2 | {2:0} | 2 found! Return [0,1] ā |
š Complexity
| Brute Force | O(n²) | O(1) |
| Hash Map | O(n) | O(n) |
šÆ Interview Variations
- Three Sum: Find triplets summing to target (sort + two pointer or hash, O(n²))
- Two Sum II (Sorted): Use two-pointer technique for O(n) time, O(1) space
- Two Sum Count: Count number of pairs (not indices). Use frequency map.
- Two Sum BST: Find if two nodes sum to target in BST (inorder + two pointer)
ā ļø Common Mistakes
- ā Returning same element twice - check indices differ
- ā Forgetting to check complement before storing current
- ā Using
array_search()which is O(n), making overall O(n²)