Two Sum (LeetCode 1): Solution and Explanation
Given an array of integers and a target, return the indices of the two different elements that add up to the target. Exactly one such pair exists, and you may not use the same element twice.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force answer writes itself: try every pair (i, j) with i < j and check whether nums[i] + nums[j] == target. That is correct but costs O(n²) time, which is about 50 million additions for an array of 10,000 numbers. The question to ask is what you are really searching for when you fix one element.
Once you are standing on nums[i], the partner you need is fully determined: it must equal target - nums[i]. So the inner loop is not really a search over pairs; it is a lookup for one specific value. Lookups for a specific value are exactly what a hash map does in constant average time. If you store each number you have seen along with its index, the question "have I seen the complement before?" becomes a single dictionary check.
That leads to a one-pass algorithm. Walk through the array once. For each element, compute the complement and check the map first. If it is there, the stored index and the current index are the answer. If not, record the current number and its index, then move on. Checking before inserting is what guarantees you never pair an element with itself, and because the earlier element of the pair is always in the map by the time you reach the later one, you can never miss the answer.
Approach: One-pass hash map
- Create an empty dictionary
prevMapthat maps each value seen so far to its index. - Iterate over the array with
enumerate, getting indexiand valuen. - Compute
diff = target - n, the value that would complete the pair. - If
diffis already inprevMap, return[prevMap[diff], i]. - Otherwise store
prevMap[n] = iand continue to the next element. - If the loop finishes without a match, return an empty list (the problem guarantees this does not happen).
Step-by-step example
nums = [3, 2, 4], target = 6
- i = 0, n = 3: diff = 3. The map is empty, so 3 is not found even though 3 + 3 = 6. Store {3: 0}.
- i = 1, n = 2: diff = 4, which is not in {3: 0}. Store {3: 0, 2: 1}.
- i = 2, n = 4: diff = 2, which is in the map at index 1. Return [1, 2].
- Notice how step one avoided pairing index 0 with itself, because the lookup happens before the insert.
Code: Python, Java, C++
1class Solution:
2 def twoSum(self, nums: List[int], target: int) -> List[int]:
3 prevMap = {} # val : index
4 for i, n in enumerate(nums):
5 diff = target - n
6 if diff in prevMap:
7 return [prevMap[diff], i]
8 prevMap[n] = i
9 return []1class Solution {
2 public int[] twoSum(int[] nums, int target) {
3 Map<Integer, Integer> map = new HashMap<>();
4 for (int i = 0; i < nums.length; i++) {
5 int diff = target - nums[i];
6 if (map.containsKey(diff)) {
7 return new int[] { map.get(diff), i };
8 }
9 map.put(nums[i], i);
10 }
11 return new int[0];
12 }
13}1class Solution {
2public:
3 vector<int> twoSum(vector<int>& nums, int target) {
4 unordered_map<int, int> m;
5 for (int i = 0; i < nums.size(); i++) {
6 int diff = target - nums[i];
7 if (m.count(diff)) {
8 return {m[diff], i};
9 }
10 m[nums[i]] = i;
11 }
12 return {};
13 }
14};Time and space complexity
O(n)
Each element is visited once, and each visit performs one dictionary lookup and at most one insert, both O(1) on average.
O(n)
In the worst case the matching pair is at the very end, so the map ends up holding nearly every element before the answer is found.
Other approaches
Brute force over all pairs (time O(n²), space O(1))
Two nested loops check every pair i < j. It needs no extra memory and is fine for tiny inputs, but it is quadratic and too slow for the upper constraint.
Sort plus two pointers (time O(n log n), space O(n))
Sort pairs of (value, original index), then move a left and right pointer inward based on whether the sum is too small or too large. It works, but sorting dominates and you must carry original indices along, so the hash map is simpler.
Common mistakes
- Inserting the current number into the map before checking for its complement. With
nums = [3, 2, 4]andtarget = 6, the first 3 would find itself and return [0, 0]. - Building the whole map first in a separate pass and then searching without checking that the found index differs from
i. A two-pass version is valid only if it rejectsprevMap[diff] == i. - Sorting the array and returning indices from the sorted copy. The problem asks for positions in the original array.
- Worrying that duplicates overwrite earlier indices. With the check-then-insert order, a duplicate that forms the answer, like [3, 3] with target 6, is found before it overwrites anything.
Frequently asked questions
Why is Two Sum O(n) with a hash map?
Each element needs only one constant time lookup to see whether its complement was seen earlier. One pass over n elements with O(1) work each gives O(n) total.
Can Two Sum be solved without extra space?
Only by giving up the linear time. The brute force uses O(1) space but O(n²) time. Sorting in place would lose the original indices unless you store them, which brings the space back.
Does the order of the returned indices matter?
Usually not; any order is accepted. This solution naturally returns the earlier index first, since that one comes from the map.
What if the array is already sorted?
Then the two-pointer technique solves it in O(n) time and O(1) space, which is the Two Sum II variant.