Find Pair with Sum in Java: Solution, Explanation & Practice

Find two numbers that add up to target

Problem summary

Write a program that finds two numbers in an array that add up to the target sum.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {2, 7, 11, 15};
        int target = 9; // Test case 1
        
        // Find pair that sums to target
        // Print: Pair: <num1>, <num2> OR No pair found
    }
}

Expected output and test cases

  • 2 + 7 = 9
    Pair: 2, 7
  • 11 + 15 = 26
    Pair: 11, 15
  • No valid pair
    No pair found

Hints

  1. Use nested loops for brute force
  2. For sorted array, use two pointers
  3. Check if arr[i] + arr[j] equals target

Validated solution

Reveal Java solution
import java.util.HashSet;
import java.util.Set;

public class Main {
    static int[] pairWithSum(int[] values, int target) {
        Set<Integer> seen = new HashSet<>();
        for (int value : values) {
            int needed = target - value;
            if (seen.contains(needed)) return new int[] {needed, value};
            seen.add(value);
        }
        return null;
    }
    public static void main(String[] args) {
        int[] pair = pairWithSum(new int[] {2, 7, 11, 15}, 9);
        System.out.println(pair == null ? "No pair found" : "Pair: " + pair[0] + ", " + pair[1]);
    }
}

How to approach the problem

For each value, calculate the complement needed to reach the target. If that complement has already appeared, a valid pair is found; otherwise remember the current value for a later match.

Approach

  1. Create an empty set of earlier values.
  2. Check target - value before inserting value.
  3. Return immediately when a complement is present.

Time and space complexity

Time: O(n) expected. Space: O(n).

Edge cases to test

  • The pair may contain the same number twice only when it occurs at two indices.
  • No pair is a normal result, not an exception.

Common mistakes

  • Adding before checking and accidentally pairing one occurrence with itself.
  • Using the sorted-array two-pointer method on an unsorted input.

Follow-up challenge

Return the original two indices rather than the two values.

Related Arrays exercises

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