Introduction
The Two Sum problem is a classic coding challenge that involves finding a pair of numbers in an array that add up to a given target value. It's a great exercise to improve your problem-solving and algorithmic thinking skills. In this article, we will explore an efficient solution to the Two Sum problem using Python.
Problem Description
Given an array of integers and a target value, our task is to find the indices of two numbers in the array that add up to the target. We can assume that each input will have exactly one solution, and we cannot use the same element twice in the pair.
Solution Approach
To solve the Two Sum problem efficiently, we can use a hashmap to store the elements of the array along with their indices. By iterating through the array once, we can check if the complement value (target minus the current element) exists in the hashmap. If it does, we have found a valid pair of numbers that add up to the target. Otherwise, we add the current element and its index to the hashmap for future reference.
Algorithm Steps
- Create an empty hashmap to store elements and their indices.
- Iterate through the array from left to right, and for each element:
- Calculate the complement value (target minus the current element).
- Check if the complement value exists in the hashmap. If it does, return the indices [hashmap[complement], current_index] as the solution.
- If the complement value does not exist in the hashmap, add the current element and its index to the hashmap.
- If no solution is found during the iteration, return an empty array.
Python Implementation
def twoSum(nums, target):
hashmap = {}
for i, num in enumerate(nums):
complement = target - num
if complement in hashmap:
return [hashmap[complement], i]
hashmap[num] = i
return []
# Example usage:
nums = [2, 7, 11, 15]
target = 9
result = twoSum(nums, target)
print(result)
Conclusion
The Two Sum problem is a common coding challenge that tests your ability to find pairs of elements that add up to a target value efficiently. By utilizing a hashmap to store elements and their indices, we can solve the problem with a time complexity of O(n). The solution presented in this article provides an elegant and efficient approach to solving the Two Sum problem using Python.