Two Sum
Easy · Arrays & hashing
Jump to codeFind the indices of two different elements of an integer array whose sum equals a target. Assume exactly one pair exists; return the indices in either order.
Examples
Example 1
nums = [2,7,11,15] target = 9
Output: [0,1]
Example 2
nums = [3,2,4] target = 6
Output: [1,2]
Constraints
- 2 <= nums.length <= 1000
- -10,000,000 <= nums[i] <= 10,000,000
- -10,000,000 <= target <= 10,000,000
- Only one valid answer exists.
Need a hint?
What information would let you find the partner of the current value immediately?
Asked in real interviews
Candidates reported versions of Two Sum from these company interviews. Some company questions are locked and open with Premium or XP.
- Find the Earliest Pair with a Target SumAmazon
- Implement lexicographically smallest Two SumWalmart Labs
- Return the Lexicographically Smallest Two-Sum Index PairGoogle
Solution approach
Scan left to right while mapping previously seen values to their indices. Before inserting x, look for target − x. Checking before insertion prevents using the same element twice. Return the saved index and the current index on a match.
Complexity
O(n) expected time and O(n) space with a hash map.
Python reference solution
def twoSum(nums, target):
seen = {}
for index, value in enumerate(nums):
partner = target - value
if partner in seen:
return [seen[partner], index]
seen[value] = index
JavaScript solution
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
const partner = target - nums[i];
if (seen.has(partner)) return [seen.get(partner), i];
seen.set(nums[i], i);
}
return [];
}
Java solution
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int partner = target - nums[i];
if (seen.containsKey(partner)) return new int[]{seen.get(partner), i};
seen.put(nums[i], i);
}
return new int[0];
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target) {
unordered_map<int, int> seen;
for (int i = 0; i < (int)nums.size(); i++) {
int partner = target - nums[i];
if (seen.count(partner)) return {seen[partner], i};
seen[nums[i]] = i;
}
return {};
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
2,
7,
11,
15
],
9
][ 0, 1 ]
[
[
3,
2,
4
],
6
][ 1, 2 ]
[
[
3,
3
],
6
][ 0, 1 ]
[
[
0,
4,
3,
0
],
0
][ 0, 3 ]
[
[
-1,
-2,
-3,
-4,
-5
],
-8
][ 2, 4 ]
Drafts are saved per language in this browser when storage is available.