Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Given int[] nums and int target, return the indices of two different elements that add up to target. Write an O(n) solution, then a solution for a sorted array with O(1) extra space.

For an unsorted array, we walk it once with a HashMap from value to index: for each i we first check whether target - nums[i] is already in the map, and if it is we return the two indices, otherwise we put nums[i]. That is O(n) time and O(n) space, and checking before inserting stops us from using the same element twice while still handling [3, 3] with target 6. For a sorted array, two pointers from both ends do it in O(n) time and O(1) space: move left up when the sum is too small and right down when it is too large, computing the sum as a long so large values cannot overflow.

Why this question is asked

Two Sum is often the first problem in an interview loop, and interviewers use it to see how we think rather than whether we know the trick. They watch whether we start from the brute force and improve it, whether we handle duplicates and the same element twice, and whether we notice overflow. The second half of the question, a sorted array with O(1) extra space, checks whether we can use a property of the input instead of a data structure. In this answer, we will start with the brute force, build the HashMap solution and see why the order of check and insert matters, write the two-pointer version and explain why it never misses a pair, deal with overflow, and finish with returning all unique pairs.

1Starting From the Brute Force

The simplest answer tries every pair: for each i, for each j greater than i, check whether nums[i] + nums[j] equals target. It is correct and uses no extra memory, but it does about n^2 / 2 additions, so for 100,000 elements that is five billion checks.

The improvement comes from asking a different question. Instead of asking which j pairs with i, we ask: for the current number x, have we already seen the number target - x? That number is called the complement. If we can answer that question in constant time, one pass is enough, and a HashMap answers it in constant time on average.

2The HashMap Solution and Why Order Matters

We keep a map from each value we have seen to its index. For each element, we look for its complement first, and only then add the element itself.

Java
static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>(); // value -> index
for (int i = 0; i < nums.length; i++) {
long need = (long) target - nums[i]; // computed as long: no overflow
if (need >= Integer.MIN_VALUE && need <= Integer.MAX_VALUE) {
Integer j = seen.get((int) need);
if (j != null) return new int[] {j, i};
}
seen.put(nums[i], i); // insert after the check
}
return new int[0]; // no pair
}
twoSum(new int[] {2, 7, 11, 15}, 9); // [0, 1]
twoSum(new int[] {3, 3}, 6); // [0, 1]
twoSum(new int[] {3, 2, 4}, 6); // [1, 2], not [0, 0]
Step throughtwoSum({3, 2, 4}, 6)
LoopMap
i=0: get(3)?
null
put(3, 0)
i=1: get(4)?
null
put(2, 1)
i=2: get(2)?
1 -> return [1, 2]

8 messages in order. Play them, or step through them one at a time.

The map only ever holds earlier elements, so the 3 at index 0 never pairs with itself.

Notice why the check comes before the put. In {3, 2, 4} with target 6, the first element is 3 and its complement is also 3. If we inserted 3 first and then looked it up, we would find index 0 and return [0, 0], using the same element twice. Checking first means the map only holds earlier elements, so a match is always a different index.

The same order handles duplicates. In {3, 3}, at i = 0 the map is empty, so we put 3 -> 0. At i = 1 the complement 3 is found at index 0, and we return [0, 1]. If the duplicates appear later than a pair we need, putting a value again overwrites its index, which is harmless because any later match only needs one earlier index.

The time is O(n) on average, because each step does one lookup and one insert. The space is O(n) for the map. In a hot path we would also notice the boxing of Integer keys; for very large inputs a primitive map from a library avoids it, but the algorithm stays the same.

3The Sorted Array With Two Pointers

When the array is sorted, we can find the pair without any map. We put one pointer at each end. If their sum is too small, the only way to make it larger is to move the left pointer to a bigger number. If it is too large, we move the right pointer to a smaller number.

Java
static int[] twoSumSorted(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left < right) {
long sum = (long) nums[left] + nums[right]; // long: no overflow
if (sum == target) return new int[] {left, right};
if (sum < target) left++; // need a bigger number
else right--; // need a smaller number
}
return new int[0];
}
twoSumSorted(new int[] {1, 3, 4, 6, 9}, 10); // 1+9=10 -> [0, 4]
twoSumSorted(new int[] {1, 3, 4, 6, 9}, 7); // 1+9=10 too big, 1+6=7 -> [0, 3]

Why can we safely skip pairs? When the sum of nums[left] and nums[right] is too large, nums[right] plus anything to the right of left is at least as large, because the array is sorted. So nums[right] cannot be part of any answer with the remaining elements, and we drop it. The same reasoning drops nums[left] when the sum is too small. Each step removes one element from consideration, so after at most n - 1 steps the pointers meet. That gives O(n) time and O(1) extra space.

If the original array is unsorted and we need original indices, sorting first costs O(n log n) and loses the positions unless we sort an array of indices instead. So we use two pointers when the input is already sorted, and the HashMap otherwise.

4Watching for Overflow

Java int arithmetic wraps around silently. With nums[left] = 2,000,000,000 and nums[right] = 1,000,000,000, the int sum is -1,294,967,296, a negative number, so the two-pointer loop would move left when it should move right and miss the pair. Casting one operand to long before adding fixes it, because a long holds any sum of two ints.

The complement in the HashMap version can overflow too. With target = Integer.MIN_VALUE and nums[i] = 1, the int expression target - nums[i] wraps to Integer.MAX_VALUE, and if that value is in the array we would report a pair whose true sum is 2,147,483,648, not the target. Computing the complement as a long and skipping values outside the int range, as in the code above, keeps the answer correct. Interviewers rarely expect this level of care, but mentioning it shows we think about real inputs.

5Follow-up questions

How would you return all unique pairs?

I would sort the array and use two pointers. When a pair matches, I record the two values, then move left forward past all equal values and right backward past all equal values, so the same pair of values is not reported twice. When the sum is too small or too large, I move one pointer as before. That is O(n log n) for the sort and O(n) for the scan, and it returns pairs of values rather than indices, which is usually what all unique pairs means. With a HashMap I could do it in one pass by keeping a set of values seen and a set of pairs already reported.

What if no pair exists, or more than one does?

The usual contract says exactly one solution exists, but I would still decide what to return when none does: an empty array, null, Optional, or an exception. I prefer an empty array or Optional over null. If several pairs exist, the HashMap version returns the pair whose second element comes first, and I would say that so the caller knows which one they get.

6Conclusion

In this answer, we went from the O(n^2) brute force to a single pass with a HashMap from value to index, where checking the complement before inserting avoids reusing an element and handles duplicates like [3, 3]. For a sorted array, two pointers moving inward find the pair in O(n) time and O(1) space, because each comparison safely rules out one element. We also saw that both the sum and the complement can overflow int, and that computing them as long keeps the answer correct.

What to say in the interviewAbout 90 seconds aloud

Open with

The brute force checks every pair and is O(n^2), so I would improve it with a HashMap from value to index. I walk the array once, and for each element I compute the complement, target minus the element, and look it up in the map.

Then, if they want more

If it is there, I return the stored index and the current index. If not, I put the current value and index in the map. The order matters: I check before I insert, so the map only contains earlier elements.

That means an element can never pair with itself, for example 3 with target 6 in the array 3, 2, 4, and it still finds the pair in 3, 3, because the first 3 is already in the map when I reach the second. That is O(n) time on average and O(n) space.

If the array is sorted, I use two pointers instead, one at each end. If the sum is too small I move the left one up, if it is too big I move the right one down. Each step rules out one element safely because of the order, so it is O(n) time and O(1) space.

One detail I always mention is overflow: two large ints can add up to a negative number, and the complement can wrap as well, so I compute the sum and the complement as long.

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 "Given int[] nums and int target, return the indices of two different elements that add...": https://scrivio-interview-library.netlify.app/java/coding-problems/0c0df39884/