0
0
JavaProgramBeginner · 2 min read

Java Program to Find Pairs with Given Sum

You can find pairs with a given sum in Java by iterating through the array and using a HashSet to check if the complement (sum - current element) exists; for example, use HashSet<Integer> set = new HashSet<>(); and check pairs while traversing.
📋

Examples

Inputarr = [1, 2, 3, 4, 5], sum = 5
Output(1, 4) (2, 3)
Inputarr = [0, -1, 2, -3, 1], sum = -2
Output(0, -2) (2, -4) (No pairs)
Inputarr = [5, 5, 5], sum = 10
Output(5, 5) (5, 5) (5, 5)
🧠

How to Think About It

To find pairs that add up to a given sum, think about each number and what other number it needs to reach that sum. For each number, check if the needed number has appeared before. If yes, you found a pair. This avoids checking every pair twice and makes the search faster.
📐

Algorithm

1
Get the input array and the target sum.
2
Create an empty set to store numbers seen so far.
3
For each number in the array, calculate the complement as sum minus the current number.
4
Check if the complement is in the set; if yes, print the pair.
5
Add the current number to the set and continue.
6
End when all numbers are processed.
💻

Code

java
import java.util.HashSet;

public class PairSum {
    public static void findPairs(int[] arr, int sum) {
        HashSet<Integer> set = new HashSet<>();
        for (int num : arr) {
            int complement = sum - num;
            if (set.contains(complement)) {
                System.out.println("(" + complement + ", " + num + ")");
            }
            set.add(num);
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int sum = 5;
        findPairs(arr, sum);
    }
}
Output
(1, 4) (2, 3)
🔍

Dry Run

Let's trace the example arr = [1, 2, 3, 4, 5] with sum = 5 through the code

1

Start with empty set

set = {}

2

Process first number 1

complement = 5 - 1 = 4; set does not contain 4; add 1 to set; set = {1}

3

Process second number 2

complement = 5 - 2 = 3; set does not contain 3; add 2 to set; set = {1, 2}

4

Process third number 3

complement = 5 - 3 = 2; set contains 2; print (2, 3); add 3 to set; set = {1, 2, 3}

5

Process fourth number 4

complement = 5 - 4 = 1; set contains 1; print (1, 4); add 4 to set; set = {1, 2, 3, 4}

6

Process fifth number 5

complement = 5 - 5 = 0; set does not contain 0; add 5 to set; set = {1, 2, 3, 4, 5}

NumberComplementSet BeforePair FoundSet After
14{}No{1}
23{1}No{1, 2}
32{1, 2}Yes (2, 3){1, 2, 3}
41{1, 2, 3}Yes (1, 4){1, 2, 3, 4}
50{1, 2, 3, 4}No{1, 2, 3, 4, 5}
💡

Why This Works

Step 1: Use a set to track seen numbers

The HashSet stores numbers we have seen so far, so we can quickly check if the complement exists.

Step 2: Calculate complement for each number

For each number, we find the number needed to reach the sum by subtracting the current number from the target sum.

Step 3: Print pairs when complement found

If the complement is already in the set, it means we found a pair that adds up to the sum, so we print it.

🔄

Alternative Approaches

Brute Force Nested Loops
java
public class PairSumBrute {
    public static void findPairs(int[] arr, int sum) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] + arr[j] == sum) {
                    System.out.println("(" + arr[i] + ", " + arr[j] + ")");
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int sum = 5;
        findPairs(arr, sum);
    }
}
Simple but slow; checks every pair, so time is O(n²).
Sorting and Two Pointers
java
import java.util.Arrays;

public class PairSumTwoPointers {
    public static void findPairs(int[] arr, int sum) {
        Arrays.sort(arr);
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int currentSum = arr[left] + arr[right];
            if (currentSum == sum) {
                System.out.println("(" + arr[left] + ", " + arr[right] + ")");
                left++;
                right--;
            } else if (currentSum < sum) {
                left++;
            } else {
                right--;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int sum = 5;
        findPairs(arr, sum);
    }
}
Faster than brute force with O(n log n) due to sorting; uses two pointers to find pairs.

Complexity: O(n) time, O(n) space

Time Complexity

The program loops through the array once, and each lookup in the HashSet is O(1) on average, so total time is O(n).

Space Complexity

The HashSet stores up to n elements in the worst case, so space complexity is O(n).

Which Approach is Fastest?

The HashSet method is fastest for unsorted arrays with O(n) time, while sorting and two pointers take O(n log n). Brute force is slowest at O(n²).

ApproachTimeSpaceBest For
HashSetO(n)O(n)Fastest for unsorted arrays
Sorting + Two PointersO(n log n)O(1)When sorting is acceptable
Brute ForceO(n²)O(1)Simple but slow, small arrays only
💡
Use a HashSet to check complements quickly and avoid nested loops.
⚠️
Beginners often forget to check if the complement exists before adding the current number to the set, missing pairs.