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

  1. Store complement (target - num) in map
  2. Check if current num is in map
  3. Map value stores index

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler