1. Introduction

Finding a pair in an array with a given sum is a recurrent problem in coding interviews. The task is to ascertain if there are two numbers in the array such that their sum equals a provided number. This post delves into the Java solution for this challenge.

2. Program Steps

1. Initialize an empty HashSet to track the numbers we’ve come across.

2. Loop through each element in the array.

3. For every element, calculate the value that, when added to the current element, will give the target sum.

4. Check if this calculated value is present in our HashSet.

5. If it is, we’ve found our pair.

6. If it isn’t, add the current element to our HashSet.

7. Continue until we either find a pair or finish checking all elements.

3. Code Program

import java.util.HashSet;

public class PairSumFinder {
    public static void main(String[] args) {
        int[] arr = {1, 2, 4, 4};
        int sum = 8;
        if (hasPairWithSum(arr, sum)) {
            System.out.println("Array has a pair with sum " + sum);
        } else {
            System.out.println("Array doesn't have a pair with sum " + sum);
        }
    }

    public static boolean hasPairWithSum(int[] arr, int sum) {
        // Create a set to store numbers we've seen so far.
        HashSet<Integer> numbers = new HashSet<>();
        for (int num : arr) {
            // Calculate the number which, when added to `num`, will give `sum`.
            int complement = sum - num;
            if (numbers.contains(complement)) {
                // If the complement is in the set, we&apos;ve found a pair.
                return true;
            }
            numbers.add(num);
        }
        return false;
    }
}

Output:

Array has a pair with sum 8

4. Step By Step Explanation

1. We begin by setting up a HashSet to help us quickly check numbers we've seen so far.

2. As we loop through each number num in the array, we calculate its complement which is the difference between the sum and the num.

3. We then check if this complement is inside our HashSet.

4. If it is, that means we've seen a number in the array which, when added to num, gives us our target sum.

5. If not, we just add the num to our set and move on.

6. If we finish looping through the array and haven't found a pair, then no such pair exists.