Two Sum: given an array of integers and a target, return the indices of the two numbers that add up to the target.

This is the Two Sum problem. Instead of checking every pair, walk through the array once and store each number's index in a HashMap. For each number, check whether target - number is already in the map.

Key Points

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> seen = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            Integer j = seen.get(target - nums[i]);
            if (j != null) {
                return new int[] {j, i};
            }
            seen.put(nums[i], i);
        }
        return new int[0];   // no pair found
    }

    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)));
    }
}

Output

[0, 1]

[1, 2]

[0, 1]

Good to Know

The [3, 3] case shows why the order matters: the first 3 is stored, and the second 3 finds it as its complement, giving two different indices.

Start by stating the O(n²) brute force, then improve it to O(n) with the HashMap; interviewers want to see that reasoning.

Interview Tip

A concise interview answer is

I loop once, and for each number check whether target minus that number is already in a HashMap of value to index; if it is, I return both indices, otherwise I store the current number. That is O(n) time and O(n) space instead of the O(n²) brute force.

Last updated: 11 November 2026

Previous question: Write a Java program to remove all whitespace from a string without using replace() or replaceAll().

Next question: Write a Java program that sorts comma-separated strings in ascending order and joins them into one string.

More Java Coding Questions interview questions

All Java Coding Questions questions