Intuition
Use a hash map to store each number's index. For each number, check if the complement (target - num) already exists in the map.
Explanation
Walk-through
- Create an empty hash map
seen. - Iterate through the array with index
iand valuenum. - Compute
complement = target - num. - If
complementis inseen, return[seen[complement], i]. - Otherwise, store
num → iinseen.
Complexity
- Time: O(n) — single pass through the array.
- Space: O(n) — hash map stores at most n entries.
Implementation
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (seen.containsKey(complement)) {
return new int[]{seen.get(complement), i};
}
seen.put(nums[i], i);
}
return new int[]{};
}
}