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 let x be represented by each individual values in our list, we can generate the y value

    • Each time we generate the y value, we can search the list if the y value exists in the list

    • If the value exists, the index of x and y will 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 = -6

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