The 30 second answer
I walk the array once and keep a HashMap from value to index. For each number I check whether target minus that number is already in the map. If it is, I return both indices, and if not, I store the current number. That is linear time and linear space, compared with the quadratic brute force over all pairs.
Problem Given an integer array and a target, return the indices of the two different positions whose values add up to the target. The problem guarantees exactly one answer. Original: LeetCode 1: Two Sum.
Understanding the prompt "Indices", not values, so sorting would lose the original positions. "Two different positions" means you can't use one element twice, but two equal values at different indices are fine.
Pattern recognition "Find two elements that combine to a target" is the complement-lookup pattern: for each element, ask whether its partner has already been seen.
Brute force Check every pair i < j. That is O(n²) time and O(1) extra space.
Optimal Use one pass with a map from value to index. Check for the complement before inserting the current value, so an element never pairs with itself.
Alternatives Sort pairs of (value, index) and run two pointers from both ends. That is O(n log n) time. It is the better choice when the input is already sorted (LeetCode 167).
Java solution
import java.util.Arrays;
import java.util.HashMap;
public class TwoSum {
static int[] twoSum(int[] nums, int target) {
var seen = new HashMap<Integer, Integer>(); // value -> index
for (int i = 0; i < nums.length; i++) {
var j = seen.get(target - nums[i]);
if (j != null) return new int[] {j, i};
seen.put(nums[i], i);
}
return new int[0]; // unreachable when exactly one answer exists
}
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[] {2, 7, 11, 15}, 9))); // [0, 1]
System.out.println(Arrays.toString(twoSum(new int[] {3, 3}, 6))); // [0, 1]
System.out.println(Arrays.toString(twoSum(new int[] {-1, -2, -3, -4}, -7))); // [2, 3]
}
}Complexity O(n) expected time, because HashMap get and put take constant time on average. O(n) extra space.
Edge cases
- Duplicate values, as in [3, 3] with target 6.
- Negative numbers.
- A complement equal to the current value: checking before inserting handles it.
Follow-ups
- Return all pairs, with or without duplicates.
- The input is sorted: use two pointers and O(1) space.
- The input arrives as a stream: keep the map and answer as items come in.
Tests [2,7,11,15] with target 9 gives [0,1]. [3,3] with target 6 gives [0,1]. Negative values: [-1,-2,-3,-4] with target -7 gives [2,3].
How to say it in the interview "The brute force checks every pair in O(n²). Instead, I store each value's index in a hash map, and for every element I look up target minus it. One pass, O(n) time, O(n) space. I look up before I insert so an element can't pair with itself."
Sources (2)
- LeetCode 1: Two Sumleetcode.com
- Java SE 17 API: HashMapdocs.oracle.com