Problem Description
Given an array of integers nums and an integer target, return indices of the two numbers in nums 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.
Examples
Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] = 2 + 7 = 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]
Python Solution
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return []
Java Solution
class Solution {
public int[] twoSum(int[] nums, int target) {
Map map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return new int[] {};
}
}
C++ Solution
class Solution {
public:
vector twoSum(vector& nums, int target) {
unordered_map map;
for (int i = 0; i < nums.size(); i++) {
int complement = target - nums[i];
if (map.find(complement) != map.end()) {
return {map[complement], i};
}
map[nums[i]] = i;
}
return {};
}
};
JavaScript Solution
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return [];
};
C# Solution
public class Solution {
public int[] TwoSum(int[] nums, int target) {
Dictionary map = new Dictionary();
for (int i = 0; i < nums.Length; i++) {
int complement = target - nums[i];
if (map.ContainsKey(complement)) {
return new int[] { map[complement], i };
}
map[nums[i]] = i;
}
return new int[] {};
}
}
Complexity Analysis
- Time Complexity: O(n) where n is the length of the input array
- Space Complexity: O(n) as we store at most n elements in the hash map
Solution Explanation
This solution uses a hash map approach:
- We use a hash map to store each number and its index as we iterate through the array
- For each number, we:
- Calculate its complement (target - current number)
- Check if the complement exists in our hash map
- If it exists, we've found our pair
- If not, we add the current number and its index to the hash map
Why this works:
- By storing numbers we've seen in a hash map, we can look up complements in O(1) time
- We only need to traverse the array once
- The hash map ensures we don't use the same element twice