What it teaches: The complement trick: for each number, look up target − number among the numbers already seen.
Practise it on judges as “Two Sum”.
The problem
Given an integer array nums and an integer target, return the indexes of the two numbers that add up to target. Exactly one solution exists, and you may not use the same element twice. Return the smaller index first.
→ Return original indexes, so sorting would lose them
→ Unsorted input
These clues point to Hash Map Lookup (Complement): As you scan, store what you've seen; for each new element, ask in O(1) whether its partner was already seen.
Stuck? Take one hint at a time
Solution.java · starter
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
return new int[0];
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Check all pairs (i, j) with i < j until one sums to target.
Approach 1
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++)
for (int j = i + 1; j < nums.length; j++)
if (nums[i] + nums[j] == target) return new int[]{i, j};
return new int[0];
}
}
Verdict: Fine for tiny inputs, about 5 × 10⁷ checks at n = 10⁴. The repeated work: searching the array again for each complement.
2
Optimal: one-pass hash map
Time O(n) Space O(n)
Keep a map from value to index for the numbers seen so far. For each nums[i], if target − nums[i] is in the map, return its index and i. Otherwise store nums[i] → i.