Two Sum
Two Sum solution for LeetCode 1, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Two Sum
What the problem is really asking
We need to find two positions in the array whose values add up to target.
The important part is that the answer wants indices, not the numbers themselves.
Intuition
When we look at a number like 7, we immediately know what we want next: target - 7.
That means every value creates a "missing partner" we should look for.
Brute-force idea
The most direct approach is to try every pair:
- check
nums[0]with every later number - then check
nums[1]with every later number - and so on
That works, but it takes O(n^2) time because there can be a lot of pairs.
Optimized approach
Instead of searching forward every time, we store what we have already seen in a hash map.
For each index i:
- compute
target - nums[i] - check whether that complement already exists in the map
- if it does, we are done
- if it does not, store
nums[i]with its index
The nice part is that hash map lookup is fast, so the whole solution becomes one pass.
Code Solution
Switch between languages
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (seen.containsKey(complement)) {
return new int[] {seen.get(complement), i};
}
seen.put(nums[i], i);
}
return new int[] {};
}
}Dry run
Take nums = [2, 7, 11, 15] and target = 9.
- start with an empty map
- at index
0, value is2, so we need7 7is not in the map, so store2 -> 0- at index
1, value is7, so we need2 2is already in the map at index0
So the answer is [0, 1].
Common mistakes
1. Storing the current number before checking the complement
If you do that, some variants of the problem can accidentally match the same element with itself.
2. Returning the values instead of the indices
The question wants positions, not the actual pair of numbers.
3. Forgetting that the map should store index information
A set is not enough here because we need to know where the earlier number came from.
Complexity
Time Complexity: O(n)
Space Complexity: O(n)
We scan the array once, and in the worst case we store almost every number in the map.
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.