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.
For example:
nums = [2,7,11,15], target = 9
should return [0,1]
because nums[0] + nums[1] == 9
.nums = [3,2,4], target = 6
should return [1,2]
.nums = [3,3], target = 6
should return [0,1]
.Explain a brute force solution, an optimal solution, and their time/space complexities. Also explain possible edge cases.
Given an array of integers nums
and an integer target
, the goal is to find two numbers within the nums
array that add up to the target
. The indices of these two numbers should be returned. It is assumed that there is exactly one solution, and the same element cannot be used twice.
A straightforward approach is to iterate through the array using nested loops. For each number, check every other number to see if their sum equals the target. This is a naive solution but helps illustrate the problem.
def twoSum_bruteForce(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 [] # No solution found
A more efficient solution involves using a hash map (dictionary in Python). The algorithm iterates through the array once. For each number, it checks if the complement (target - number) is already in the hash map. If it is, the indices of the current number and its complement are returned. If not, the current number and its index are added 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 [] # No solution found
The optimal solution using a hash map significantly improves the time complexity from O(n^2) to O(n), making it more efficient for large input arrays. The space complexity increases to O(n), but this is a reasonable trade-off for the improved time performance.