1. Two Sum
Description
See the description in the Two Sum question.
Solution
We need to find two numbers in the array that sum to the target value. The problem definition states "return indices of the two numbers such that they add up to target."
The wording made me think of x + y = target. But, when approaching problems, see if the equation can be rewritten that will make it easier to solve. In this case target - x = y.
When iterating through an array we will have the target value and the current item value (x). So, we want to find a value for y that solves the equation.
There are two approaches for finding y. One uses a cache, and the other uses two pointers. There is also a brute force solution of using nested loops, but it is too slow.
Cache Solution
I initially solved it using a cache. It is the easier of the two solutions for this question. In this solution, each element of the array is cached as the array is iterated over. It is then a matter of checking the array to see if y exists in it.
Two Pointer Solution
However, the problem can also be solved using two pointers. The two pointers method is used for solving the Three Sum problem.
Sort the array.
Initialize two pointers (left, right) to the first and last positions in the array.
Sum the values of the left and right elements.
If the result is greater than the target value, then move the right pointer to the left (and hence resulting in a smaller sum the next time).
If the result is less than the result, then move the left pointer needs to the right (resulting in a greater sum the next time).
Repeat step 3 until the summation equals the target. (The question states there will be one unique answer)
Example:
input = [11, 7, 4, 15], target = 18
sort the array: [4, 7, 11, 15]
initialize pointers: left = 0 (start of the array) right = 3
iterate through the array summing the left and right index values and moving the left and right pointers as appropriate:
0
0
3
4 + 15 = 19
1
0
2
4 + 11 = 15
2
1
2
7 + 11 = 18
Last updated