Thursday, May 26, 2022

[Solved] How to find all pairs which add up to a given value in an Integer Array in Java? Example

Hello guys, if you are preparing for programming job interview then you know that the problem of finding all pairs which adds up to a given value in a give array is a popular array based coding question. This question is also known as Two sum problem because you need to find pair of two elements in the array whose sum is equal to given number. For example, you have given an array of integers with values {1, 2, 3, 4, 5, 6} and you need to find all the pairs whose sum is equal to 5. In this case, there are two such pairs (1, 4) and (2, 3) so your program needs to print them into console. 

Before we jump into solution, its important that you understand the problem and working through examples are based way to understand the problem. Always ask for sample input and sample output before solving the question. 

In order to solve this question, you need to scan through the array, you can use two pointers one from left and one right to scan the array. The key thing to remember is whether the given array is sorted or not. If array is not sorted then its better to sort the array before scanning. 

If array is sorted then first element is the lowest and last element is highest. If the sum of first and last element is equals to given sum then both pointer should move towards each other to find other pairs but if its less than given sum then the second pointer should move towards first pointer. Similarly, if given sum is more than the sum of first and last element then first pointer should move towards second pointer to find the first pair. 

This will be more clear when you see the code and how it process different input. You can also debug the program into your favorite IDE like Eclipse or IntelliJIDEA to understand then program better. 





Given an array of Integer, find all pairs which adds up to a given value - Java Example

Here is our complete Java program to solve the Two sum problem and print all the pairs which adds up to a given value in an integer array. In this program, I have created a static method called printPairs(int[] input, int givenSum) which takes an integer array and the given sum as input and print all the pairs whose sum is equal to given number into console. 

How to find all pairs which adds upto a given value in an Integer Array in Java? Example



/**
* Java program to solve problem, Given an array of Integer, find all pairs,
* which adds upto a given value e.g. k. Don't need to output pair in reverse
* order e.g. if desired output is 5 then (3,2) and (2,3) is same pair. Also
* pair must be of two distinct number e.g. for desired output of 10, (5,5) is
* not a pair.
*
* @author Javin Paul
*/
public class Testing {

    public static void main(String args[]) {
        printPairs(new int[]{1, 2, 3, 4, 5, 6}, 5);
        printPairs(new int[]{0, 5, 7, 9, 11, 2}, 12);
        printPairs(new int[]{1, 2, -3, 4, -5, 6}, 2);
        printPairs(new int[]{1, 0, 1, 4, 2, 6}, 10);
        printPairs(new int[]{11, 21, 31, 41, 51, 61}, 32);
        printPairs(new int[]{1, 2, 3, 4, 5, 6}, 15);

        showPairs(new int[]{1, 2, 3, 4, 5, 6}, 5);
        showPairs(new int[]{0, 5, 7, 9, 11, 2}, 12);
        showPairs(new int[]{1, 2, -3, 4, -5, 6}, 2);
        showPairs(new int[]{1, 0, 1, 4, 2, 6}, 10);
        showPairs(new int[]{11, 21, 31, 41, 51, 61}, 32);
        showPairs(new int[]{1, 2, 3, 4, 5, 6}, 15);
    }

    public static void printPairs(int[] numbers, int k) {
        if (numbers.length < 2) {
            throw new IllegalArgumentException("Array must contain atleast two numbers");
        }
        System.out.println("printPairs() input: " + Arrays.toString(numbers)
                + ", and desired sum is : " + k);
        Arrays.sort(numbers);
        int left = 0;
        int right = numbers.length - 1;
        boolean pairFound = false;
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == k) {
                pairFound = true;
                System.out.printf("Pairs with sum %d is(%d, %d) %n",
                        k, numbers[left], numbers[right]);
                left = left + 1;
            } else if (sum < k) {
                left += 1;
            } else {
                right -= 1;
            }
        }

        if (!pairFound) {
            System.out.println("Sorry no matching pair found for given sum " + k);
        }
    }

    public static void showPairs(int[] integers, int desired) {
        System.out.println("showPairs(), input : " + Arrays.toString(integers) 
          + ", sum : " + desired);
        HashMap<Integer, Integer> visited = new HashMap<>();
        boolean pairFound = false;

        for (int number : integers) {
            if (visited.get(desired - number) != null) {
                pairFound = true;
                System.out.printf("Pair Found (%s, %s) %n", number, desired - number);
            } else {
                // put number to Map, key is number itself and value will be
                // (desired - number)
                visited.put(number, (desired - number));
            }
        }
        if (!pairFound) {
            System.out.println("No pair found for desired sum " + desired);
        }
    }

}

Output:
printPairs() input: [1, 2, 3, 4, 5, 6], and desired sum is : 5
Pairs with sum 5 is(1, 4)
Pairs with sum 5 is(2, 3)
printPairs() input: [0, 5, 7, 9, 11, 2], and desired sum is : 12
Pairs with sum 12 is(5, 7)
printPairs() input: [1, 2, -3, 4, -5, 6], and desired sum is : 2
Sorry no matching pair found for given sum 2
printPairs() input: [1, 0, 1, 4, 2, 6], and desired sum is : 10
Pairs with sum 10 is(4, 6)
printPairs() input: [11, 21, 31, 41, 51, 61], and desired sum is : 32
Pairs with sum 32 is(11, 21)
printPairs() input: [1, 2, 3, 4, 5, 6], and desired sum is : 15
Sorry no matching pair found for given sum 15
showPairs(), input : [1, 2, 3, 4, 5, 6], sum : 5
Pair Found (3, 2)
Pair Found (4, 1)
showPairs(), input : [0, 5, 7, 9, 11, 2], sum : 12
Pair Found (7, 5)
showPairs(), input : [1, 2, -3, 4, -5, 6], sum : 2
No pair found for desired sum 2
showPairs(), input : [1, 0, 1, 4, 2, 6], sum : 10
Pair Found (6, 4)
showPairs(), input : [11, 21, 31, 41, 51, 61], sum : 32
Pair Found (21, 11)
showPairs(), input : [1, 2, 3, 4, 5, 6], sum : 15
No pair found for desired sum 15


That's all about how to find all pairs in array which adds to a given number in Java. I have showed two ways to solve this problem, one uses traditional for loop and other uses the for each loop of Java 5. I have also included validation in code as they are necessary in any real world application. Interviewer also impress with this approach as this shows that you are better than other developers who neglect input validations. 

Other Coding Problems for Practice
  • How to Print duplicate characters from String? (solution)
  • How to Find duplicate characters in a String? (solution)
  • How to Check if String is Palindrome? (solution)
  • Reverse String in Java using Iteration and Recursion? (solution)
  • Find the highest occurred character in a String? (solution)
  • Check if a String contains only digits?  (solution)
  • 20+ array-based coding problems from interviews (questions)
  • 10 free Data Structure Courses for Beginners (Free DSA courses)
  • Find the first non-repeated character from String? (solution)
  • How to count the occurrence of a given character in String? (solution)
  • How to convert numeric string to an int? (solution)
  • Reverse words in a sentence without using a library method? (solution)
  • Reverse a String in place in Java? (solution)
  • Count the number of vowels and consonants in a String? (solution)
  • My favorite free course to learn Data Structure and Algorithms (courses)

Thanks for reading this article so far. If you like this problem and my solution then please share with your friends and colleagues. If you have any questions or feedback then please drop a note and I will be happy to help you. 

P.S. - If you are preparing for Technical Job Interview and you need more such questions, you can also  check the Data Structures and Algorithms Bootcamp course on  Udemy. This is a great online course to build and level up your Data Structure and Algorithms skills to become a better programmer.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.