Two Sum Problem – Python

This task aims to find two distinct numbers in a given list that sum up to a specified target value. The output should be the indices of these two numbers. For instance, given the input list [2, 7, 11, 15] and a target sum of 9, the expected output is [0, 1], which corresponds to the index of the numbers 2 and 7.

Implementation

def two_sum(nums, target):
    num_to_index = {}
    
    for index, num in enumerate(nums):
        complement = target - num
        if complement in num_to_index:
            return [num_to_index[complement], index]
        num_to_index[num] = index
    
    return None  # Return None if no solution is found

# Example usage
input_list = [2, 7, 11, 15]
target_sum = 9
result = two_sum(input_list, target_sum)
print(result)  # Output: [0, 1]

The above code defines a function two_sum that takes two parameters: nums, a list of integers, and target, an integer representing the desired sum.

  1. We start by initializing an empty dictionary called num_to_index. This dictionary will map each number in the list to its corresponding index.
  2. Then we use the enumerate function to loop through the list, which gives us both the index and the number at that index.
  3. For each number, we calculate its complement by subtracting the number from the target. This complement represents the number we need to find to achieve the target sum.
  4. We check if this complement exists in our dictionary. If it does, we have found our two numbers and return their indices as a list.
  5. If the complement is not found, we add the current number and its index to the dictionary for future reference.
  6. If no such pair is found by the end of the loop, the function returns None.