-1

I am looking out for efficient approach to the solution of th eproblem that is .. write a program to find all pairs of integers whose sum is equal to a given number. For example if input integer array is {2, 6, 3, 9, 11} and given sum is 9, output should be {6,3}

now what I have tried is that below but i know this not a feasible and efficient solution..

To take one number from array and then loop through array and output pairs which is equal to given sum. You do this for all numbers in first array,

import java.util.Arrays;

/**
 * Java Program to find pairs on integer array whose sum is equal to k

 */
public class ProblemInArray{

    public static void main(String args[]) {
        int[] numbers = { 2, 4, 3, 5, 7, 8, 9 };
        int[] numbersWithDuplicates = { 2, 4, 3, 5, 6, -2, 4, 7, 8, 9 };
        prettyPrint(numbers, 7);
        prettyPrint(numbersWithDuplicates, 7);
    }

    /**
     * Prints all pair of integer values from given array whose sum is is equal to given number.
     * complexity of this solution is O(n^2)
     */
    public static void printPairs(int[] array, int sum) {

        for (int i = 0; i < array.length; i++) {
            int first = array[i];
            for (int j = i + 1; j < array.length; j++) {
                int second = array[j];

                if ((first + second) == sum) {
                    System.out.printf("(%d, %d) %n", first, second);
                }
            }

        }
    }
    /**
     * Utility method to print input and output for better explanation.
     */
    public static void prettyPrint(int[] givenArray, int givenSum){
        System.out.println("Given array : " + Arrays.toString(givenArray));
        System.out.println("Given sum : " + givenSum);
        System.out.println("Integer numbers, whose sum is equal to value : " + givenSum);
        printPairs(givenArray, givenSum);
    }

}

Output:
Given sum : 7
Integer numbers, whose sum is equal to value : 7
(2, 5) 
(4, 3) 
Given array : [2, 4, 3, 5, 6, -2, 4, 7, 8, 9]
Given sum : 7
Integer numbers, whose sum is equal to value : 7
(2, 5) 
(4, 3) 
(3, 4) 
(-2, 9) 

2 Answers2

3

You could use a HashMap. If the desired sum - the current item hits an exising value you can be sure that this is a possible match. Otherwise add the current item an go on. This should be run in O(n).

public static final void sums(final int sum, final int[] numbers){
    HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
    for(int i : numbers){
        if(map.containsKey(sum-i)){
             System.out.println("( "+map.get(sum-i) +" "+ i+" )");
        }else{
            map.put(i,i);
        }
    }
}
user
  • 735
  • 1
  • 6
  • 21
  • I think that `HashSet` would be better suited for that than `HashMap` (because you just want to test for existence, not map the value to something else). – Florent Bayle Oct 14 '14 at 10:27
  • @Florent Bayle This was my first thought. In case of Integers this would be the better choice, because you can avoid the set.get() method by a simple substraction of sum - i to get the missing value, but with more complex types i think a map is a better solution. – user Oct 14 '14 at 10:32
  • Nice attempt. Just 2 suggestions: 1)Try to add condition so that the pairs doesn't get repeated , like (2,5) and (5,2) 2) Avoid same number to make pair, like: (4,4) for sum 8 . One more thing, your print statement System.out.println(map.get(sum-i) + i); will keep printing the sum repeatedly, considering separating map.get(sum-i) and i. – Tarek Oct 14 '14 at 11:06
0

This is my code:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class FindPairs {
    public static void main(String args[]) {
        Integer[] numbers = { 2, 4, 3, 5, 7, 8, 9 };
        int sum = 7;
        List<Integer> Numbers = Arrays.asList(numbers);
        Collections.sort(Numbers);
        for (int i : Numbers) {
            if (Numbers.contains(sum - i) && i <= (sum / 2) && i != (sum - i)) {
                System.out.print((sum - i) + " & ");
                System.out.println(+i);
            }
        }
    }
}

The condition i<=(sum/2) is required to prevent double repetition of pairs (2 & 5) and (5 & 2). The condition i!=(sum-i) is required to prevent same number in paring. (For example, if your sum is 8, then if you don't use this condition, you will also get pair (4,4) ).

Answer:

5 & 2

4 & 3

Tarek
  • 771
  • 7
  • 18