Two Sum in Java: Program and Logic
Return the indices of the two array elements that add up to a target.
- Time
O(n) on average - Space
O(n) - Hints3
- Read3 min
To solve two sum in Java, loop once over the array and keep a HashMap from each value to its index. For every nums[i], look up target - nums[i] in the map. If it is there, return the stored index and i. If not, save nums[i] with its index. This takes O(n) time on average and O(n) space.
Problem statement
The two sum Java question gives you an int array nums and an int target.
Return the indices of two different elements whose sum equals target.
You may not use the same position twice.
If there is no such pair, return an empty array. If several pairs work, returning the first one your loop completes is fine here.
The answer is positions, not values. For the version that only asks for the two values, see find a pair with a given sum, which uses a HashSet.
An integer array nums of length n and an integer target.
Two indices in increasing order, or an empty array if no pair exists.
Examples
nums = [2, 7, 11, 15], target = 9[0, 1]nums[0] + nums[1] = 2 + 7 = 9.
nums = [3, 2, 4], target = 6[1, 2]2 + 4 = 6. Index 0 alone (3 + 3) is not allowed because it uses one element twice.
nums = [3, 3], target = 6[0, 1]Equal values are fine because they sit at different indices.
Constraints
- 0 <= n <= 10^5
- Each value and the target fit in an int
- An element cannot be paired with itself
Think before you code
Reveal the questions to ask yourself first
- If you are standing at
nums[i], which single number would finish the sum? - Where could you store earlier numbers so that you can find one quickly?
- You need a position at the end. What must you store next to each number?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Way 1: brute force. Try every pair with two loops. It needs no extra memory, but the time is O(n²).
static int[] bruteForce(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if ((long) nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
Starting j at i + 1 avoids pairing an element with itself.
Way 2: two sum Java using HashMap. Remove the inner loop:
- Create an empty map: key = value seen, value = its index.
- For each index
i, computeneed = target - nums[i]. - If the map has
need, return its index andi. - Otherwise store
nums[i]with indexi. - If the loop ends, return an empty array.
New to maps? Read HashMap in Java first.
Dry run
Walk through the example step by step
nums = [3, 2, 4], target = 6:
i | nums[i] | need | in map? | map after the step
--+---------+------+---------+-------------------
0 | 3 | 3 | no | {3=0}
1 | 2 | 4 | no | {3=0, 2=1}
2 | 4 | 2 | yes, 1 | return [1, 2]
At i = 0 the map is still empty, so 3 cannot be paired with itself.
Solution
Reveal the full Java solution
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> indexOf = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
long need = (long) target - nums[i];
if (need >= Integer.MIN_VALUE && need <= Integer.MAX_VALUE) {
Integer j = indexOf.get((int) need);
if (j != null) {
return new int[]{j, i};
}
}
indexOf.put(nums[i], i);
}
return new int[0];
}
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[]{2, 7, 11, 15}, 9)));
System.out.println(Arrays.toString(twoSum(new int[]{3, 2, 4}, 6)));
System.out.println(Arrays.toString(twoSum(new int[]{3, 3}, 6)));
System.out.println(Arrays.toString(twoSum(new int[]{1, 2}, 10)));
}
}Output of this two sum Java code:
[0, 1]
[1, 2]
[0, 1]
[]
- The stored index
jalways comes beforei, so the answer is in increasing order. - We use
longforneedbecausetarget - nums[i]can go past the int limit. An int result would wrap around and could match a wrong value. - We call
getonce and compare withnull. That is one lookup, wherecontainsKeyfollowed bygetwould be two.
Two sum Java program with user input
This shorter version assumes small numbers, so it uses plain int.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class TwoSumInput {
// Sample input: 4 10 20 30 40 50
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
int target = sc.nextInt();
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < n; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) {
System.out.println("Indices: " + j + " and " + i);
return;
}
seen.put(nums[i], i);
}
System.out.println("No pair found");
}
}
The input is the size, then the elements, then the target. Output for the sample input:
Indices: 1 and 2
Which two sum Java solution should you give?
| Method | Time | Extra space | Gives original indices? |
|---|---|---|---|
| Two loops | O(n²) | O(1) | Yes |
| HashMap, one pass | O(n) average | O(n) | Yes |
| Sort + two pointers | O(n log n) | O(n) if you save the indices | Only if you save them first |
Say the two-loop idea in one line, then code the HashMap version. Be ready to explain how HashMap works inside, because "average O(1)" is a likely follow-up. More practice: Java coding interview questions and the Java full stack course.
O(n) on averageO(n)Review before the interview
Common mistakes
- Putting the current value in the map before the lookup, which can pair an element with itself.
- Returning values when the question asks for indices.
- Sorting the array and then returning sorted positions as if they were the original ones.
- Using int for target - nums[i] when values can be near the int limits.
Edge cases to test
- Empty array or one element: no pair, so return an empty array.
- Duplicates such as [3, 3] with target 6.
- Negative numbers, zero, and a target of 0.
- No valid pair at all.
Interview follow-ups
- How do you return every pair of indices and not just the first?
- The array is already sorted. Can you do it with O(1) extra space?
- How would you extend the idea to three sum?
Keep practising
Find a Pair With a Given Sum in an Array
Hints · Dry run · SolutionSolve Similar problemCount the Frequency of Each Element in an Array
Hints · Dry run · SolutionSolve Similar problemFind the Missing Number in an Array of 1 to N
Hints · Dry run · SolutionSolve Related learningHashmap
TutorialLearn Related learningArrays
TutorialLearn Related learningCoding Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
