need = target − n
seen hash map · value → index · bucket = value mod 8
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> seen = new HashMap<>(); // value -> index for (int i = 0; i < nums.length; i++) { int n = nums[i]; int need = target - n; if (seen.containsKey(need)) { return new int[] { seen.get(need), i }; } seen.put(n, i); } return new int[0];}
- i
- —
- n
- —
- need
- —
- need mod 8
- —
- seen
- {}
Why it works
- Brute force tries every pair: two nested loops, O(n²).
- Flip the question. For each
nyou already know the partner you need:target − n. The map answers "have I seen it?" in O(1) on average. - Look up before you store. Otherwise
ncould pair with itself: in[3,2,4]with target 6, the 3 must not match its own 3. - Store value → index, because the answer asks for indices, not values. A repeated value overwrites its index; either index is a valid answer.
- One pass: a pair is found the moment its second number arrives. O(n) time, O(n) space.
- Sorted input? Then two pointers from both ends need no map, O(1) space. That is Two Sum II, the same idea you meet again in Valid Palindrome.