Two Sum in Java Explained: Brute Force and the HashMap Trick
-
Last Updated: July 9, 2026
-
By: javahandson
-
Series
Learn Java in a easy way
Learn the Two Sum in Java problem step by step. See the brute-force solution, the fast HashMap approach, a full dry run, and clear, beginner-friendly code.
The Two Sum problem in Java is usually the first question people meet when they start with arrays. It looks tiny. Yet it teaches a habit that shows up in dozens of harder problems later. So it is worth slowing down and really getting it.
Here is the task in plain words. You get an array of numbers and one target value. You must find two numbers that add up to the target. Then you return their positions in the array.
In this guide, we start with the slow but obvious way. After that, we speed it up with a clever trick using a HashMap. We also dry-run the code by hand, so you can see exactly what happens on each step. By the end, this problem will feel simple.
Let us pin down the rules first. A clear problem statement saves you from silly bugs later.
So, for the array above with a target of 9, the answer is [0, 1]. Why? Because nums[0] is 2 and nums[1] is 7, and 2 plus 7 equals 9. Notice that we return positions, not the numbers themselves. Beginners mix this up all the time.
| 💡 Interview Insight Interviewers often ask whether the array is sorted. Two Sum does not assume sorting. If the array were sorted, a two-pointer approach would also work. Mentioning that difference early shows you are thinking ahead. |
The first idea most people have is simple. Check every possible pair of numbers. If any pair adds up to the target, return those two positions.
for i from 0 to n-1:
for j from i+1 to n-1:
if nums[i] + nums[j] == target:
return [i, j]
return [] // no pair foundThe outer loop picks the first number. The inner loop picks a later number to pair with it. We start j at i plus 1, so we never pair a number with itself. Also, this avoids checking the same pair twice.
public class TwoSumBrute {
public static int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
return new int[] {}; // no answer
}
public static void main(String[] args) {
int[] nums = { 2, 7, 11, 15 };
int[] ans = twoSum(nums, 9);
System.out.println(ans[0] + ", " + ans[1]); // 0, 1
}
}Let us walk through the code slowly. Each line has a clear job.
This code is easy to read and hard to get wrong. That is its main strength. The problem is speed, which we will fix next.
The brute force checks roughly every pair. For an array of size n, that is about n times n over two comparisons. So the time is O(n2). The space stays O(1) because we only use a few variables. For small arrays, this is fine. For large ones, it gets slow quickly.
Now for the smart version. The key idea is to remember the numbers we have already seen. As we walk the array once, we ask a simple question at each step. Have I already seen the number I still need?
For each number, the number we need is the target minus the current number. If that needed number sits in our memory, we are done. If not, we store the current number and move on.
seen = empty map // value -> index
for i from 0 to n-1:
need = target - nums[i]
if need is in seen:
return [seen[need], i]
seen[nums[i]] = i
return []import java.util.HashMap;
public class TwoSumHashMap {
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (seen.containsKey(need)) {
return new int[] { seen.get(need), i };
}
seen.put(nums[i], i);
}
return new int[] {};
}
public static void main(String[] args) {
int[] nums = { 2, 7, 11, 15 };
int[] ans = twoSum(nums, 9);
System.out.println(ans[0] + ", " + ans[1]); // 0, 1
}
}This version does more thinking, so let us break it down gently.
Because a HashMap lookup is fast on average, each check takes constant time. So one pass through the array is enough. That single change is what makes this approach shine.
| 💡 Interview Insight A classic follow-up asks why we store the value as the key and the index as the value. The reason is our lookup is by value, not by position. We search for a needed value, so that value must be the key. |
Watching the code run by hand makes it stick. Let us use nums = [2, 7, 11, 15] and target = 9. We track the map as it changes.
| Step | i | nums[i] | need = target – nums[i] | seen the map before | Action |
|---|---|---|---|---|---|
| 1 | 0 | 2 | 9 – 2 = 7 | { } (empty) | 7 not found. Store 2 -> 0 |
| 2 | 1 | 7 | 9 – 7 = 2 | { 2 : 0 } | 2 found! Return [0, 1] |
Look at step two closely. We reach the number 7. Its partner is 2, and 2 is already sitting in the map from step one. So we return the stored index 0 with the current index 1. That gives us [0, 1], and we never even touch 11 or 15.

The sketch above shows the same trace. The array sits on top, the memory map sits below, and the arrows show how 7 finds its partner 2. Many people find this picture easier than the table, so use whichever one clicks for you.
Both approaches return the correct answer. They just pay different prices. Here is the plain comparison.
In an interview, start by mentioning the brute force. It shows you understand the problem. Then improve it with the HashMap to show you can optimize. That path from slow to fast is exactly what interviewers want to see.
| 💡 Interview Insight Strong candidates say the quiet part out loud: the HashMap trades space for time. That single sentence signals you understand the real cost, not just the Big-O letters. |
A few small traps catch beginners on this problem. Keep these in mind.
The Two Sum problem in Java looks like a warm-up, and it is. But the HashMap trick inside it is a real skill. You will reuse that same remember-as-you-go idea in many tougher array and string problems.
So take the lesson, not just the answer. Brute force first to be safe. Then reach for a HashMap when you need speed. Once that pattern feels natural, a whole family of problems opens up for you.
Two Sum asks you to find two numbers in an array that add up to a given target and return their indexes. Each input has exactly one valid answer, and you cannot reuse the same element twice.
The HashMap approach is fastest. You walk the array once, and for each number, you check whether its partner (the target minus the number) is already in the map. This runs in O(n) time because each lookup is constant on average.
The brute force uses two nested loops, so it runs in O(n2) time and O(1) space. It is simple and correct, but it slows down fast as the array grows.
You return the indexes, not the values. This is the most common mistake beginners make. For nums = [2, 7, 11, 15] and target 9, the answer is [0, 1], not [2, 7].
Yes. The math works the same for negatives and zeros. Duplicates are also handled correctly because the HashMap approach checks for the needed value before storing the current number.
You now have Two Sum in your toolkit, so let us keep the momentum going. The next problem in this series is a classic that builds the same one-pass habit you just learned.