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

list = [2,7,11,15]

all sum pairs:
    2 + 7 = 9
    2 + 11 = 13
    2 + 15 = 17
    7 + 11 = 18
    7 + 15 = 22
    11 + 15 = 26

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

# INSERT PSEUDOCODE HERE

Python Solution

def twoSum(array: list[int], target: int) -> list[int]:
    answer = []
    
    for i in range(len(array)):
        left_operand = array[i]
        
        for j in range(i+1, len(array)):
            right_operand = array[j]
            
            if left_operand + right_operand == target:
                answer.append(i)
                answer.append(j)
                return answer
            # end of if
        # end of inner for
    # end of outer for
    
    # return empty list if solution not found
    return []
# end of twoSum()

Code Explanation

def twoSum(array: list[int], target: int) -> list[int]:
  • The function twoSum is defined to take two arguments:

    • array: a list of integers.

    • target: an integer.

  • The function returns a list of integers.

answer = []
  • An empty list answer is initialized to store the indices of the two numbers that add up to the target, if found.

for i in range(len(array)):
    left_operand = array[i]
  • This loop iterates through the array using index i.

  • left_operand is set to the value at index i of the array.

for j in range(i+1, len(array)):
    right_operand = array[j]
  • 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 index j of the array.

if left_operand + right_operand == target:
    answer.append(i)
    answer.append(j)
    return answer
  • The sum of left_operand and right_operand is checked against the target.

  • If the sum equals the target, the indices i and j are appended to the answer list.

  • The function returns the answer list immediately after finding the pair, as the problem typically asks for just one such pair.

return []
  • 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