Two Sum with HashMap in Java: Explanation & Practice
Find pair with target sum using HashMap
Problem summary
Use HashMap to find two numbers that add up to target in O(n) time.
Starter code
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9; // Test case 1
// Find pair using HashMap
// Print: Indices: <i>, <j>
}
}Expected output and test cases
- 2 + 7 = 9
Indices: 0, 1
- Different pair
Indices: 1, 2
- No valid pair
No pair found
Hints
- Store complement (target - num) in map
- Check if current num is in map
- Map value stores index
Related Collections exercises
- Practice Simple LRU Cache in Java
- Practice Priority Queue with Custom Order in Java
- Practice First Unique Element in Java
Practice all Collections exercises · Run this idea in the Java compiler