Code Logo

Two Sum Indices

Published at16 Mar 2026
Easy 8 views
Like0

You are given an array of numbers and a target sum. You need to return the two indices whose values add up to that target.

The answer is about positions, not the values themselves. So if nums = [2,7,11,15] and target = 9, the correct answer is [0,1] because nums[0] + nums[1] = 9. If nums = [3,2,4] and target = 6, the answer is [1,2].

You also cannot reuse the same index twice. That is why [3,3] with target 6 uses both positions and returns [0,1].

So the task is to find the matching pair of positions whose values combine to the target.

Example Input & Output

Example 1
Input
nums = [2,7,11,15], target = 9
Output
[0,1]
Explanation

2 + 7 = 9.

Example 2
Input
nums = [3,2,4], target = 6
Output
[1,2]
Explanation

2 + 4 = 6.

Example 3
Input
nums = [3,3], target = 6
Output
[0,1]
Explanation

Both values 3 are used.

Algorithm Flow

Recommendation Algorithm Flow for Two Sum Indices
Recommendation Algorithm Flow for Two Sum Indices

Solution Approach

The standard hash table approach is to scan from left to right while remembering the numbers we have already seen and where they were found.

At each index i, suppose the current value is num. Instead of searching the whole array for a partner, compute the value we need: needed = target - num.

If that needed value has already appeared earlier, then we already know its index from the map, and we can return the pair immediately. If it has not appeared yet, store the current number and its index in the map and continue.

The order matters. We check for the partner first, then store the current number. That prevents us from accidentally using the same index twice.

The core logic is:

const seen = new Map(); for (let i = 0; i < nums.length; i++) { const num = nums[i]; const needed = target - num; if (seen.has(needed)) return [seen.get(needed), i]; seen.set(num, i); }

This works well even when duplicate values exist, because the map stores earlier indices as we go. The full solution runs in O(n) time with O(n) extra space, which is much better than checking every possible pair.

Best Answers

java
import java.util.*;
class Solution {
    public int[] two_sum_indices(int[] nums, int target) {
        Map<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[]{};
    }
}