Python Code Example: Finding Pairs with Target Sum

In this Python tutorial, we will learn how to find all pairs of numbers in a list that add up to a given target sum. This is a common problem in coding interviews and data processing applications. We will iterate through the list, check for pairs that sum to the target value, and store them. This technique is useful in various scenarios, such as detecting complementary values in financial transactions or solving array-based problems efficiently.

Code Example

# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target_sum = 10

# List to store pairs
pairs = []

# Finding pairs that sum up to the target
for i in range(len(numbers)):
    for j in range(i + 1, len(numbers)):  # Avoid duplicate pairs
        if numbers[i] + numbers[j] == target_sum:
            pairs.append((numbers[i], numbers[j]))

# Output the pairs
print("Pairs with target sum:", pairs)

Output

Pairs with target sum: [(1, 9), (2, 8), (3, 7), (4, 6)]

Code Explanation

  1. List of Numbers & Target Sum: We define a list numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] and set the target sum as 10.
  2. Using Nested Loops:
    • The outer loop iterates through each number in the list.
    • The inner loop starts from the next element (i + 1) to avoid checking the same pair twice.
  3. Checking for Target Sum:
    • We check if the sum of numbers[i] + numbers[j] equals target_sum.
    • If the condition is met, we add the pair (numbers[i], numbers[j]) to the pairs list.
  4. Avoiding Duplicate Pairs:
    • Since we start the inner loop from i + 1, we ensure that each pair is checked only once.
    • This prevents reversed duplicates like (9,1) when (1,9) is already found.
  5. Output: The final list of pairs is printed.

This approach efficiently finds all unique pairs that sum up to the target value. It can be optimized using a set-based lookup to reduce time complexity from O(n2)O(n^2)O(n2) to O(n)O(n)O(n).