Find Pair with Sum in Java: 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
- Use nested loops for brute force
- For sorted array, use two pointers
- Check if arr[i] + arr[j] equals target
Related Arrays exercises
Practice all Arrays exercises · Run this idea in the Java compiler