Two Sum
Easy
Topics
Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.
You may assume exactly one solution, and you may not use the same element twice. Return the answer in any order.
Example 1
[0, 1], not their values.Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: nums[0] + nums[1] == 9.
Example 2
Input: nums = [3,2,4], target = 6 Output: [1,2]
Constraints
- 2 <= nums.length <= 10^4
- -10^9 <= nums[i] <= 10^9
- Exactly one valid answer exists.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The brute force checks every pair — for each i, scan every j after it. That is O(n²) and wasteful because we keep re-scanning numbers we have already seen.
The key realization: for a fixed number x, there is exactly one number that completes the pair — its complement target - x. So instead of searching for it, we can remember every number we have passed in a hash map and check for the complement in O(1).
Approach
- Create a hash map from value → index.
- Iterate once. For the current value
x, computeneed = target - x. - If
needis already a key in the map, we have found the two numbers — return[map[need], i]. - Otherwise record
x → iand move on. We store after checking so an element is never paired with itself.
Walkthrough
nums = [2, 7, 11, 15], target = 9
i=0 x=2 need=7 map={} -> 7 not seen, store 2:0
i=1 x=7 need=2 map={2:0} -> 2 IS seen -> return [0, 1]Complexity
- Time — O(n): a single pass; each hash-map lookup and insert is O(1) on average.
- Space — O(n): in the worst case the map stores nearly every element before the matching pair appears.
Common Pitfalls
- Storing the value in the map before checking would let an element match itself.
- Return indices, not the values themselves.
Full Solution — all languages
class Solution:
def twoSum(self, nums, target):
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
return []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++) {
if (seen.containsKey(target - nums[i])) return new int[]{seen.get(target - nums[i]), i};
seen.put(nums[i], i);
}
return new int[]{};
}
}#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++) {
if (seen.count(target - nums[i])) return {
seen[target - nums[i]], i
};
seen[nums[i]] = i;
}
return {
};
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/ var twoSum = function(nums, target) {
const seen = {};
for (let i = 0; i < nums.length; i++) {
if ((target - nums[i]) in seen) return [seen[target - nums[i]], i];
seen[nums[i]] = i;
}
return [];
};