Generate all possible pairs of values
Solution Breakdown
If we have all pairs of values, we can create a sum from each pair to compare it with the target.
The indices that generated the pair that totals to the target will be our answer
Example of generating all possible sums
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
The function
twoSum
is defined to take two arguments:array
: a list of integers.target
: an integer.
The function returns a list of integers.
An empty list
answer
is initialized to store the indices of the two numbers that add up to the target, if found.
This loop iterates through the array using index
i
.left_operand
is set to the value at indexi
of the array.
This loop iterates through the array starting from
i+1
to avoid considering the same element twice and to avoid duplicates.right_operand
is set to the value at indexj
of the array.
The sum of
left_operand
andright_operand
is checked against thetarget
.If the sum equals the target, the indices
i
andj
are appended to theanswer
list.The function returns the
answer
list immediately after finding the pair, as the problem typically asks for just one such pair.
If no such pair is found after checking all possible pairs, the function returns an empty list.
Connected Readings
Type Hinting Functions (Link)
Last updated