Home > Software engineering >  Display pairs of numbers whose sum equals to another element in the same array
Display pairs of numbers whose sum equals to another element in the same array

Time:11-10

Example: {10,4,6,-1,23,11,5}

Output: (4,6),(-1,5),(6,5)

The reasoning behind this is the fact that 4 6=10, -1 5=4, and 6 5=11

The mentioned pairs add up to another existent value in the same array, and it doesn't matter which order they are displayed in

I did the classic brute-force, with 3 nested for-loops, on paper using a pen (this is the test that I had for a paid academy..)

And of course it is not ok - and thus I require your help, thank you!

CodePudding user response:

You can save one loop by storing the elements in the given array in a hashmap first.

Then the innermost loop which searches whether the element in a set can be changed to a O(1) query of hashmap

CodePudding user response:

Here a simple answer with 2 for loops:

    int sum;
    for(int i=0; i<arr.size()-1; i  ) {
        for(int j=i 1; j<arr.size(); j  ) {
            sum = arr.get(i)   arr.get(j);
            if(arr.contains(sum)) {
                System.out.println(arr.get(i)  "," arr.get(j));
            }
            sum = 0;
        }
    }

arr is the ArrayList with all the numbers.

The method arr.get(i) gives you the value that is in the index i in the arrylist.

The method arr.contains(sum) return true if the objects sum is in the arraylist, and false if not.

  • Related