Subtract each value from the target, see if the difference exists in the list
Solution Breakdown
Since a sum is a result of two operands added together, we can express it as ->
x + y = sum
By rearranging the equation, we can also express it as ->
y = sum - x
If we have the
sum
set to our given target value, and letx
be represented by each individual values in our list, we can generate they
valueEach time we generate the
y
value, we can search the list if they
value exists in the listIf the value exists, the index of
x
andy
will be our pair that generated our desired target value
Example of looking at differences
Depending what our target value is, the sum generated by each possible pair creates such numbers. As long as the target value is one of the results (9, 13, 17, 18, 22, 26)
, we should be able to locate the two index values that adds up to the target.
Pseudocode
Python Solution
Code Explanation
asd
Optimizing the Solution with a Dictionary
Doing only a single traversal through the dictionary
Connected Readings
Last updated