Math, asked by JAYANTH9150, 1 year ago

find four elements a b c and d in an array such that a+b = c+d

Answers

Answered by devil815
0
Given an array of distinct integers, find if there are two pairs (a, b) and (c, d) such that a+b = c+d, and a, b, c and d are distinct elements. If there are multiple answers, then print any of them.

Example:

Input: {3, 4, 7, 1, 2, 9, 8} Output: (3, 8) and (4, 7) Explanation: 3+8 = 4+7 Input: {3, 4, 7, 1, 12, 9}; Output: (4, 12) and (7, 9) Explanation: 4+12 = 7+9 Input: {65, 30, 7, 90, 1, 9, 8}; Output: No pairs found

Expected Time Complexity: O(n2)

hope it helps!!!☺
Answered by dcepks
0

If you know programming  in java

public static ArrayList<Integer> find(int[] num,int n){

 ArrayList<Integer> ans = new ArrayList<>();

 HashMap<Integer,Pair> hm = new HashMap<>();

 for (int i = 0; i < n; i++) {

  for (int j = i+1; j < n; j++) {

   if (i == j) {

   } else {

    int x = num[i] + num[j];

    if (!hm.containsKey(x)) {

     hm.put(x, new Pair(i, j));

    } else {

     Pair p = hm.get(x);

     ans.add(p.n1);

     ans.add(p.n2);

     ans.add(i);

     ans.add(j);

//      ans.add(e)

     return ans;

     

     

    }

   }

  }

 }

 return new ArrayList<>();

 

}

 

public static class Pair{

 int n1;

 int n2;

 public Pair(int n1,int n2) {

  this.n1 = n1;

  this.n2 = n2;

 }

}

}

Similar questions