Video in progress
Find the indexes of two elements in an array whose sum equals a given number, in O(n).
I walk the array once, and for each number I check in a HashMap whether target - number was seen earlier. If it was, we found the pair; if not, I put the current number into the map with its index.
📖 Answer
Checking every pair with two loops is O(n²). The interviewer usually hears that solution and asks "can it be faster?".
static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>(); // value -> index
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];
}
Why do we check first and add afterwards? With [3, 5] and target = 6, in the reverse order the 3 would pair with itself.
Repeated values work correctly too: [3, 3], target = 6. When the second 3 arrives, the first one is already in the map.
If the array is already sorted, you don't even need the map: it's solved with two pointers in O(1) memory. Clarify this with the interviewer, because the answer changes.
Sign up to mark studied questions and save your progress.