The Two Sum problem is a classic algorithmic challenge often encountered in coding interviews and platforms like LeetCode. Here's a comprehensive guide on how to approach and solve it effectively.
Problem Statement
Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.
You may assume:
- Each input has exactly one solution.
- You may not use the same element twice.
Example:
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9
Approaches to Solve the Problem
There are multiple ways to solve the Two Sum problem. We'll discuss two primary methods: the Brute Force approach and the Hash Map (also known as a dictionary) approach.
1. Brute Force Approach
Idea:
- Check every possible pair of numbers to see if they add up to the target.
Steps:
- Iterate through the array with the first pointer
i.
- For each
i, iterate through the array again with a second pointer j starting from i + 1.
- Check if
nums[i] + nums[j] equals the target.
- If they do, return the indices
[i, j].
Time Complexity: O(n²), where n is the number of elements in nums.
Space Complexity: O(1), constant space.
Python Implementation:
def two_sum_brute_force(nums, target):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
return []
Explanation:
- The outer loop picks the first element.
- The inner loop picks the second element.
- If their sum matches the target, their indices are returned.
Drawbacks:
- Inefficient for large datasets due to its quadratic time complexity.
2. Hash Map (Dictionary) Approach
Idea:
- Use a hash map to store the numbers and their corresponding indices as you iterate through the array.
- For each element, check if the complement (
target - current_number) exists in the hash map.
Steps:
- Initialize an empty hash map (dictionary) to store numbers and their indices.
- Iterate through the array with index
i and value num.
- For each
num, calculate its complement (complement = target - num).
- Check if the complement exists in the hash map:
- If yes, return the indices
[hash_map[complement], i].
- If no, add
num and its index i to the hash map.
- If no such pair is found after the iteration, return an empty list.
Time Complexity: O(n), where n is the number of elements in nums.
Space Complexity: O(n), for storing the elements in the hash map.
Python Implementation:
def two_sum_hash_map(nums, target):
num_to_index = {} # Initialize the hash map
for i, num in enumerate(nums):
complement = target - num
if complement in num_to_index:
return [num_to_index[complement], i]
num_to_index[num] = i # Store the index of the current number
return []
Explanation:
num_to_index = {}: Initializes an empty dictionary to store numbers and their indices.
for i, num in enumerate(nums):: Iterates through the array with both index and value.
complement = target - num: Calculates the number needed to reach the target when added to the current number.
if complement in num_to_index:: Checks if the complement has already been seen.
- If yes, returns the pair of indices
[num_to_index[complement], i].
num_to_index[num] = i: If the complement isn't found, stores the current number and its index in the hash map.
Advantages:
- Efficiency: Solves the problem in linear time, making it suitable for large datasets.
- Single Pass: The solution traverses the array only once.
Choosing the Right Approach
While the brute force method is straightforward, its inefficiency makes it impractical for large inputs. The hash map approach, though slightly more complex, offers a much better performance and is the preferred solution for the Two Sum problem.
Complete Example
Let's walk through a complete example using the hash map approach.
Input:
nums = [3, 2, 4]
target = 6
Step-by-Step Execution:
-
Initialization:
-
First Iteration (i = 0, num = 3):
complement = 6 - 3 = 3
3 is not in num_to_index.
- Store
3 with index 0: num_to_index = {3: 0}
-
Second Iteration (i = 1, num = 2):
complement = 6 - 2 = 4
4 is not in num_to_index.
- Store
2 with index 1: num_to_index = {2: 1, 3: 0}
-
Third Iteration (i = 2, num = 4):
complement = 6 - 4 = 2
2 is in num_to_index with index 1.
- Return
[1, 2]
Output:
[1, 2]
Explanation:
nums[1] + nums[2] = 2 + 4 = 6, which matches the target.
Conclusion
The Two Sum problem exemplifies how choosing the right data structure (like a hash map) can significantly optimize your solution. Understanding various approaches not only helps in solving this particular problem but also equips you with strategies applicable to a wide range of algorithmic challenges.
Feel free to implement the solutions in your preferred programming language and test them with different inputs to deepen your understanding!