Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations.
So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster?
The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
function twoSum($nums, $target) {
$map = [];
foreach ($nums as $i => $num) {
if (isset($map[$target - $num])) {
return [$map[$target - $num], $i];
}
$map[$num] = $i;
}
return [];
}
// Test
$nums = [2, 7, 11, 15];
$target = 9;
print_r( twoSum($nums, 9) );
class TwoSum(object):
def solution(self, nums, target):
required = {}
for i in range(len(nums)):
if target - nums[i] in required:
return [required[target - nums[i]], i]
else:
required[nums[i]] = i
# Test
class TwoSumTest(unittest.TestCase):
def setUp(self) -> None:
self.s = TwoSum()
def test_solution(self):
self.assertEqual(self.s.solution([3, 2, 4], 6), [1, 2])
function twoSum(nums, target) {
let map = {};
for (let i = 0; i < nums.length; i++) {
let complement = target - nums[i];
if (complement in map) {
return [map[complement], i];
}
map[nums[i]] = i;
}
return [];
}
// Test
console.log( twoSum([2, 7, 11, 15], 9) );