Array of Doubled Pairs in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of integers A with even length, now we have to say true if and only if it is possible to reorder it in such a way that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2. So if the input is like [3,1,3,6] then the result will be false, where as [4,-2,2,-4], will return true.

To solve this, we will follow these steps −

  • Create a map m, n := size of A, store the frequency of each element in A into map m

  • cnt := size of A

  • for each key-value pair kv in map

    • if m[key of kv] > 0, then

      • if m[key of kv] is not 0 and m[2* key of kv] > 0

        • x := min of m[key of kv] and m[2* key of kv]

        • cnt := cnt – (x * 2)

        • decrease m[2 * key of kv] by x

        • decrease m[key of kv] by x

      • otherwise when key of kv = 0, then

        • cnt := cnt – m[key of kv]

        • m[key of kv] := 0

  • return false when cnt is non-zero, otherwise true

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool canReorderDoubled(vector<int>& A) {
      map <int, int> m;
      int n = A.size();
      for(int i = 0; i < n; i++){
         m[A[i]]++;
      }
      int cnt = A.size();
      map <int, int> :: iterator it = m.begin();
      while(it != m.end()){
         if(m[it->first] > 0){
            if(it->first != 0 && m[it->first * 2] > 0){
               int x = min(m[it->first], m[it->first * 2]);
               cnt -= (x * 2);
               m[it->first * 2] -= x;
               m[it->first] -= x;
            }else if(it->first == 0){
               cnt -= m[it->first];
               m[it->first] = 0;
            }
         }
         it++;
      }
      return !cnt;
   }
};
main(){
   vector<int> v1 = {3,1,3,6};
   Solution ob;
   cout << (ob.canReorderDoubled(v1)) << endl;
   v1 = {4,-2,2,-4};
   cout << (ob.canReorderDoubled(v1));
}

Input

[3,1,3,6]
[4,-2,2,-4]

Output

0
1
raja
Published on 10-Apr-2020 13:49:48
Advertisements