Two sum problem explained: from brute force to hash map
Walk through Two Sum from brute force to an O(n) hash map solution in JavaScript, with complexity analysis and common mistakes.

Two Sum is often the first problem people meet when they start practising data structures and algorithms. It looks tiny, but it teaches one of the most useful ideas in coding interviews: trading a little memory for a lot of speed.
This is the two sum problem explained step by step in JavaScript. We start with the obvious brute-force solution, see why it is slow, and then improve it to an O(n) two sum hash map solution. Along the way you will see two sum time complexity for each approach, the edge cases that trip people up, and a list of similar problems to try next. If you searched for two sum LeetCode explained, this walkthrough covers the same problem in plain language.
Problem statement and examples
Here is the problem in simple words:
You are given an array of integers nums and an integer target. Return the indices of the two numbers that add up to target.
The usual rules are:
Each input has exactly one valid answer.
You cannot use the same element twice.
You can return the answer in any order.
Example 1
js
nums = [2, 7, 11, 15]
target = 9
// Output: [0, 1]
// Because nums[0] + nums[1] = 2 + 7 = 9Example 2
js
nums = [3, 2, 4]
target = 6
// Output: [1, 2]
// Because 2 + 4 = 6. Note that 3 + 3 would be wrong: you cannot reuse index 0.Example 3
js
nums = [3, 3]
target = 6
// Output: [0, 1]
// Duplicate values are fine, as long as they are at different indices.Notice that the answer is the indices, not the values. This matters later when we think about sorting.
Brute-force approach
The most natural idea is to try every possible pair. Pick the first number, check it against every number after it, then move to the next number and repeat.
The idea in steps
Take the number at index
i.For every index
jafteri, check whethernums[i] + nums[j]equals the target.If it does, return
[i, j].If no pair works, return an empty array.
Code in JavaScript
js
function twoSum(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return [];
}We start j at i + 1 so that we never use the same element twice, and we never check the same pair in both orders.
Complexity of the brute-force solution
Time: O(n²), because of two nested loops.
Space: O(1), because we only use a few variables.
This solution is correct, and for small arrays it is perfectly fine. It is also a good thing to say first in an interview: start with a simple correct solution, then improve it.
Why it is slow
For an array of n numbers, the brute-force method checks about n × (n − 1) / 2 pairs. That number grows fast.
With 10 numbers, that is about 45 checks.
With 1,000 numbers, about half a million checks.
With 100,000 numbers, nearly 5 billion checks.
That last case is far too slow for a coding test, so you would see a "Time Limit Exceeded" error even though your logic is right.
The waste is easy to see. For each number, we scan the whole rest of the array just to ask one question: "Is there a number equal to target - nums[i] somewhere?" We keep answering the same type of question by searching again and again.
If we could answer that question quickly, without scanning, the problem would get much faster. That is exactly what a hash map is good at.
Hash map approach
A hash map (a Map in JavaScript) lets you check whether a key exists, and fetch its value, in O(1) time on average.
The key insight
For each number x, the number we need is target - x. This is called the complement. Instead of searching the array for the complement, we remember the numbers we have already seen in a map and look the complement up instantly.
The idea in steps
Create an empty map. It will store each number we have seen, along with its index.
Go through the array once.
For the current number, compute
need = target - nums[i].If
needis already in the map, we have found our pair. Return the stored index ofneedand the current index.Otherwise, store the current number and its index in the map, and move on.
Dry run with nums = [2, 7, 11, 15] and target = 9
i = 0, number is 2. We need 7. The map is empty, so 7 is not there. Store2 → 0.i = 1, number is 7. We need 2. The map has 2 at index 0. Return[0, 1].
Dry run with nums = [3, 2, 4] and target = 6
i = 0, number is 3. We need 3. The map is empty, so we do not find it. Store3 → 0.i = 1, number is 2. We need 4. Not in the map. Store2 → 1.i = 2, number is 4. We need 2. The map has 2 at index 1. Return[1, 2].
Notice how the "reuse the same element" trap is avoided automatically. At i = 0, we look for the complement before we store the current number, so the number cannot match itself.
Code in JavaScript
js
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) {
return [seen.get(need), i];
}
seen.set(nums[i], i);
}
return [];
}
console.log(twoSum([2, 7, 11, 15], 9)); // [0, 1]
console.log(twoSum([3, 2, 4], 6)); // [1, 2]
console.log(twoSum([3, 3], 6)); // [0, 1]Complexity of the hash map solution
Time: O(n). We loop through the array once, and each map lookup and insert is O(1) on average.
Space: O(n). In the worst case, we store almost every number in the map.
The trade-off
We improved the time from O(n²) to O(n), but we paid for it with O(n) extra memory instead of O(1). This is a classic time and space trade-off, and interviewers love to hear you explain it. A short, clear way to say it is: "I use a hash map to remember numbers I have seen, so I can find each complement in constant time. That makes it O(n) time and O(n) space."
A note on the order of operations
We check the map first and store the current number second. If you store first and check second, then a number could find itself as its own complement, for example nums = [3, 2, 4] with a target of 6 would wrongly pair index 0 with itself.
Edge cases
Good solutions handle the awkward inputs too. Test these before you submit.
1. Duplicate numbers
nums = [3, 3], target = 6 should return [0, 1]. Our solution works because the first 3 is stored before the second 3 looks for its complement.
2. Zero as a value or an index
If you check the map with a plain if (seen[need]), index 0 is falsy in JavaScript, and the code would wrongly say "not found". That is why we use seen.has(need), which checks for the key itself and not the truthiness of the value.
3. Negative numbers
nums = [-3, 4, 3, 90], target = 0 should return [0, 2]. The same logic works, because the complement is just target - x, whether it is positive or negative.
4. The target is zero or the numbers are zero
nums = [0, 4, 3, 0], target = 0 should return [0, 3]. This combines duplicates and zeros, so it is a good test.
5. The same element twice
nums = [3, 2, 4], target = 6 must not return [0, 0]. Our order of operations (check first, store after) prevents this.
6. No valid pair
In the original problem, an answer always exists. But in a variation, or in your own tests, there may be none. Our code returns an empty array in that case. State clearly what you would return, such as [] or null.
7. Very small arrays
An array with 0 or 1 elements cannot have a pair. The loops simply finish and return [].
8. Large values
JavaScript numbers are safe up to about 9 quadrillion for whole numbers, so ordinary input sizes are fine. If the problem involves huge numbers, mention it as a consideration.
What about sorting?
Another idea is to sort the array and use two pointers, one at each end. That is a good approach when the array is already sorted, and it uses O(1) extra space. But if you sort an unsorted array, you lose the original indices, and since this problem asks for indices, you would need to store them separately. The hash map solution is simpler here.
Similar problems to try next
Once Two Sum feels comfortable, these problems use the same ideas.
Two Sum II (sorted array): The input is already sorted, so you can use two pointers and O(1) extra space.
3Sum: Find all unique triplets that add up to zero. Sort first, then fix one number and run a two-pointer search on the rest.
Contains Duplicate: Use a set to remember what you have seen, just like our map.
Valid Anagram: Use a frequency map to compare two strings.
Group Anagrams: Use a map to group words that share the same letters.
Subarray Sum Equals K: Use prefix sums together with a hash map, an extension of today's idea.
Longest Consecutive Sequence: Use a set to find streaks of numbers in O(n).
Two Sum with a data structure: Design a class that supports adding numbers and checking for a pair, which makes you think about the trade-off between fast adds and fast searches.
A good way to practise
For each new problem, first write down the brute-force solution and its complexity. Then ask: "What am I searching for repeatedly, and could a map or set answer it faster?" That question solves a large share of beginner and intermediate problems.
FAQs
What is the time complexity of the Two Sum hash map solution?
It is O(n) time and O(n) space. We pass through the array once, and each lookup and insertion in the map takes O(1) on average.
Why is the brute-force Two Sum solution O(n²)?
Because it uses two nested loops. For each of the n numbers, it checks up to n other numbers, which gives about n² checks.
Why do we store the index in the map?
Because the problem asks for the indices of the two numbers, not the numbers themselves. The map stores each number as the key and its index as the value.
Can Two Sum be solved without extra space?
If the array is sorted, you can use two pointers with O(1) extra space. For an unsorted array, the brute-force solution uses O(1) space but is O(n²) in time. The hash map is the standard way to get O(n) time.
Should I use an object or a Map in JavaScript?
Both work, but Map is cleaner here. It handles any kind of key, keeps insertion order and avoids surprises with inherited object properties. If you use a plain object, check with in or hasOwnProperty, not with a truthy test.
What if there are multiple valid pairs?
The original problem guarantees one answer. If a variation has several, our solution returns the first pair it finds. To collect all pairs, you would keep going instead of returning early, and think carefully about duplicates.
Is sorting a good approach for Two Sum?
Sorting gives O(n log n) time with two pointers, but it breaks the original index positions. You would have to store the indices along with the values. The hash map approach is simpler and faster for this version of the problem.
How do I explain this solution in an interview?
Start with the brute force and its O(n²) time. Then explain the insight: for each number, you need its complement, and a hash map finds it in constant time. Mention the O(n) time and O(n) space trade-off, and walk through a small example out loud.
Is Two Sum asked in real interviews?
It is one of the most commonly practised starter problems, and variations of its pattern appear often. Even if you are not asked this exact problem, the "remember what you have seen in a map" idea is useful in many others.
Practise, then compare
Reading a solution is only half the job. Close this page and write both versions from memory, then test them on the edge cases above. Try the similar problems on The Zift and compare your solution.
