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 <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- Only one valid answer exists.
Follow-up:Ā Can you come up with an algorithm that is less thanĀ Ā time complexity?
Solution
Concept
The task is to find two indices and in the array nums
such that:
We have the following constraints:
- Each input will have exactly one solution.
- Indices and must be distinct.
- The solution must be efficient, ideally better than .
Naive Approach
- Use two nested loops to check every pair of numbers in the array.
- For each pair, check if their sum equals the target.
- Return the indices if a match is found.
Time Complexity: (inefficient for large arrays).
Optimized Approach: Using a Hash Map
The optimized solution uses a hash map (dictionary) to store the difference between the target and each element as we iterate through the array.
Steps:
- Create an empty hash map to store values weāve seen so far as key-value pairs.
- Traverse the array. For each number, calculate its complement:
- Check if the complement exists in the hash map:
- If it does, return the current index and the index of the complement.
- If it doesnāt, add the current number and its index to the hash map.
- Continue until the solution is found (guaranteed as per constraints).
Time Complexity: , since we traverse the array once. Space Complexity: , for the hash map.
Implementation
Here are some implementations of the optimized solution:
Example Walkthrough
Example 1
Input: nums = [2, 7, 11, 15]
, target = 9
- Start with
num_map = {}
. - Iterate:
- , , :
7
is not innum_map
.- Add
2
to the map:num_map = {2: 0}
.
- , , :
2
is innum_map
with index0
.- Return
[0, 1]
.
- , , :
Output: [0, 1]
Example 2
Input: nums = [3, 2, 4]
, target = 6
- Start with
num_map = {}
. - Iterate:
- , , :
3
is not innum_map
.- Add
3
to the map:num_map = {3: 0}
.
- , , :
4
is not innum_map
.- Add
2
to the map:num_map = {3: 0, 2: 1}
.
- , , :
2
is innum_map
with index1
.- Return
[1, 2]
.
- , , :
Output: [1, 2]