Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
Follow-up: Can you come up with an algorithm that is less than O(n^2)
time complexity?
## Two Sum Problem
This problem asks us to find two numbers in an array that add up to a specific target value. Let's explore a couple of approaches.
### 1. Brute Force Approach
The most straightforward solution is to iterate through each element of the array and check its sum with every other element. If we find a pair that adds up to the target, we return their indices.
```python
def twoSum_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 None # No solution found
# Example Usage
nums = [2, 7, 11, 15]
target = 9
result = twoSum_brute_force(nums, target)
print(result) # Output: [0, 1]
A more efficient approach involves using a hash map (dictionary in Python). We iterate through the array, and for each number, we check if the complement (target - number) exists in the hash map. If it does, we have found our pair. If not, we add the number and its index to the hash map.
def twoSum_optimal(nums, target):
num_map = {}
for index, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], index]
num_map[num] = index
return None # No solution found
# Example Usage
nums = [2, 7, 11, 15]
target = 9
result = twoSum_optimal(nums, target)
print(result) # Output: [0, 1]
None
(or raise an exception, depending on the specific requirements).Here's the code including some error handling for edge cases:
def twoSum_optimal_with_edge_cases(nums, target):
if not nums:
return None # Handle empty array case
num_map = {}
for index, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], index]
num_map[num] = index
return None # No solution found