Two Sum (Unsorted) in Java: Explanation & Practice

Find two numbers that add up to target using HashMap

Problem summary

Given an unsorted array and target, find two numbers that add up to target. Use HashMap for O(n) solution.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        
        // Store complement in HashMap
        // For each num, check if (target - num) exists
        // Print: Indices: 0, 1
    }
}

Expected output and test cases

  • [2,7,11,15], target=9
    Indices: 0, 1
  • [3,2,4], target=6
    Indices: 1, 2
  • [3,3], target=6
    Indices: 0, 1

Hints

  1. For each number, its complement is target - number
  2. Store each number with its index in HashMap
  3. Before storing, check if complement already exists
  4. If yes, we found our pair!

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler