Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a method that returns the indices of two numbers in an int[] that add up to a target, in one pass. Explain the time and space complexity and what changes if the array is sorted.

We walk the array once with a HashMap from value to index: for each a[i] we first check whether target - a[i] is already in the map, and if it is we return both indexes; only then do we put a[i]. That is O(n) time and O(n) space, with boxing overhead for large inputs. If the array is sorted, two pointers moving in from both ends find the pair in O(n) time and O(1) space.

Why this question is asked

Two Sum is probably the most asked warm-up question in coding interviews, and it is popular for a reason: it shows whether we can trade memory for time with a hash map, whether we notice the subtle bug of using one element twice, and whether we adapt when the input has extra structure such as being sorted. In this answer, we will start from the brute force solution, build the one-pass HashMap version and explain why the order of check and put matters, look at the real memory cost of boxing, solve the sorted variant with two pointers, and finish with the overflow trap at extreme values.

1Starting From the Brute Force

The simplest solution checks every pair: for each i, look at every j greater than i and test whether a[i] + a[j] equals the target. It is correct and uses no extra memory, but it does about n squared over two comparisons. For n = 100,000 that is 5 billion pairs, which takes seconds. The question asks for one pass, so we need a way to answer the question 'have I already seen the number that completes this one?' in constant time. That is exactly what a hash map does.

2The One-Pass HashMap Solution

For each element a[i], the partner it needs is complement = target - a[i]. We keep a HashMap from each value we have already passed to its index. If the complement is in the map, we have found the pair. Otherwise we record a[i] and move on.

Java
static int[] twoSum(int[] a, int target) {
Map<Integer, Integer> seen = new HashMap<>(); // value -> index
for (int i = 0; i < a.length; i++) {
int complement = target - a[i];
Integer j = seen.get(complement); // check first
if (j != null) return new int[] {j, i};
seen.put(a[i], i); // then remember a[i]
}
return new int[0]; // or throw, if a pair must exist
}
System.out.println(Arrays.toString(twoSum(new int[] {2, 7, 11, 15}, 9))); // [0, 1]
System.out.println(Arrays.toString(twoSum(new int[] {3, 2, 4}, 6))); // [1, 2]
System.out.println(Arrays.toString(twoSum(new int[] {3, 3}, 6))); // [0, 1]
Step throughOne pass over {3, 2, 4} with target 6
  1. i = 0, a[i] = 3, need 3map is empty: put 3 -> 0
  2. i = 1, a[i] = 2, need 44 not in map: put 2 -> 1
  3. i = 2, a[i] = 4, need 22 found at index 1
  4. Return [1, 2]

4 steps in order. Play them, or step through them one at a time.

At i = 0 the map is still empty, so 3 cannot be paired with itself.

Each iteration does one get and one put, both O(1) on average, so the loop is O(n). In the worst case the map stores n entries, so space is O(n). If the same value appears several times, put overwrites the older index, which is fine because we only need one valid pair.

3Why We Check Before We Put

The order of the two lines inside the loop is the subtle part. If we put a[i] into the map before looking up the complement, then for the input {3, 2, 4} with target 6, the very first element 3 finds its complement 3, which is itself, and we return [0, 0]. That uses the same element twice, which the problem forbids.

Java
// Broken: put before check
seen.put(a[i], i);
Integer j = seen.get(target - a[i]);
if (j != null) return new int[] {j, i};
// twoSum({3, 2, 4}, 6) -> [0, 0], wrong: element 0 used twice

By checking first, the map only contains elements strictly before i, so a match is always a different element. And notice that this order still handles {3, 3} correctly: at i = 1, the first 3 is already in the map with index 0, so we return [0, 1]. A two-pass version that fills the map first must instead check j != i explicitly.

4The Hidden Cost of Boxing

O(n) space hides a large constant in Java. A HashMap<Integer, Integer> cannot store int directly; each key and value is an Integer object, and each entry is a HashMap.Node object as well. On a typical 64-bit JVM with compressed references, one entry costs around 50 to 70 bytes once we count the node, the two Integer objects outside the small cache from -128 to 127, and the table slot. For 10 million elements that is several hundred megabytes and a lot of garbage collection work.

For large inputs we have two better options. A primitive map from a library such as fastutil's Int2IntOpenHashMap or Eclipse Collections' IntIntHashMap stores ints in plain arrays and uses a fraction of the memory. Or, if we can afford O(n log n), we sort a copy of the indexes by value and use two pointers, which needs no map at all.

5When the Array Is Sorted: Two Pointers

If the array is sorted in ascending order, we do not need a map. We put one pointer at the start and one at the end. If their sum is too small, the only way to increase it is to move the left pointer right, because every element to its right is larger. If the sum is too large, we move the right pointer left. Each step discards one element that cannot be part of any answer, so after at most n steps we find the pair or the pointers meet.

Java
static int[] twoSumSorted(int[] a, int target) {
int lo = 0, hi = a.length - 1;
while (lo < hi) {
long sum = (long) a[lo] + a[hi]; // long avoids overflow
if (sum == target) return new int[] {lo, hi};
if (sum < target) lo++; else hi--;
}
return new int[0];
}
System.out.println(Arrays.toString(twoSumSorted(new int[] {1, 3, 4, 6, 9}, 10))); // [0, 4]
System.out.println(Arrays.toString(twoSumSorted(new int[] {1, 3, 4, 6, 9}, 7))); // [1, 2]
Choosing an approach
ApproachTimeSpace
Brute force pairsO(n^2)O(1)
One-pass HashMapO(n)O(n), boxed
Sort, then two pointersO(n log n)O(n) for index pairs
Two pointers on sorted inputO(n)O(1)

This is O(n) time and O(1) space, strictly better than the map when the input is already sorted. If it is not sorted, sorting costs O(n log n) and loses the original indexes unless we sort index pairs, so the hash map is the better choice for unsorted input.

6Watching for Integer Overflow

At extreme values, int arithmetic wraps around silently. If target is Integer.MIN_VALUE and a[i] is 1, then target - a[i] overflows to Integer.MAX_VALUE, and we look up a complement that is not the real one. With wrap-around both the subtraction and the comparison happen in the same modular arithmetic, so the HashMap version usually still finds a correct pair, but it can also report a pair whose real sum is not the target, for example when two large positives wrap to a negative target. The safe fix is to compute in long, as the sorted version does with (long) a[lo] + a[hi], or to use Math.subtractExact, which throws ArithmeticException instead of wrapping. In an interview, mentioning this shows we think about the full range of inputs, not only the happy path.

7Follow-up questions

What if we need all pairs, not just one?

We keep a map from value to a count or a list of indexes, and for each element add every earlier index of its complement to the result. The output itself can be O(n^2) for inputs like all equal values, so the time is O(n + number of pairs). If we only need distinct value pairs, a set of seen values and a set of reported pairs is enough.

How would you extend this to three numbers adding up to a target?

Sort the array, then for each index i run the two pointer search on the part to its right with target - a[i]. That gives O(n^2) time and O(1) extra space, and skipping equal neighbours avoids duplicate triples.

Why not use containsKey and then get?

It works but performs two hash lookups. A single get that returns null for a missing key does the same job in one lookup, which matters in a tight loop over millions of elements.

8Conclusion

In this answer, we solved Two Sum in one pass with a HashMap from value to index, checking for target - a[i] before putting a[i] so that an element is never paired with itself. It runs in O(n) time and O(n) space, and boxing makes that space large for big inputs, where a primitive map helps. For sorted input, two pointers from both ends give O(n) time and O(1) space. Finally, we guarded against int overflow in target - a[i] by using long arithmetic or the exact math methods.

What to say in the interviewAbout 90 seconds aloud

Open with

I would walk the array once and keep a HashMap from each value I have seen to its index. For each element I compute the complement, target minus a of i, and look it up first.

Then, if they want more

If it is there, I return the stored index and i. Only after the check do I put a of i into the map. That order matters: if I put first, an element can match itself, for example three with a target of six would return index zero twice.

Checking first still handles two equal values like three and three, because the first one is already in the map when I reach the second. Each step is one get and one put, so the time is O(n) and the space is O(n) in the worst case.

In Java the space is bigger than it looks, because keys and values are boxed Integers and each entry is a node object, so for tens of millions of elements I would use a primitive int map.

If the array is sorted, I do not need a map at all: I put one pointer at each end, move the left one right when the sum is too small and the right one left when it is too large, which is O(n) time and O(1) space.

And I would compute sums in long, or use Math.subtractExact, so extreme values near Integer.MIN_VALUE cannot overflow silently.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a method that returns the indices of two numbers in an int[] that add up to a...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/60cafe209f/