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 = sumBy rearranging the equation, we can also express it as ->
y = sum - xIf we have the
sumset to our given target value, and letxbe represented by each individual values in our list, we can generate theyvalueEach time we generate the
yvalue, we can search the list if theyvalue exists in the listIf the value exists, the index of
xandywill be our pair that generated our desired target value
Example of looking at differences
list = [2,7,11,15]; target = 9
all possible differences:
9 - 2 = 7
9 - 7 = 2
9 - 11 = -2
9 - 15 = -6Depending 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