Skip to content
Related Articles

Related Articles

Improve Article

Check if an array arr[] can be rearranged such that arr[2 × i + 1] = 2* arr[2 × i] for every ith index

  • Last Updated : 31 May, 2021

Given an array arr[] consisting of 2*N integers, the task is to check if it is possible to rearrange the array elements such that arr[2 * i + 1] = 2* arr[2 * i] for every ith index. If it is possible to do so, then print “Yes. Otherwise, print “No”.

Examples:

Input: arr[] = {4, -2, 2, -4}, N = 2
Output: Yes
Explanation: Rearrange the array as arr[] = {-2, -4, 2, 4}.

Input: arr[] = {3, 1, 3, 6}, N = 2
Output: No

Approach: The idea to solve the given problem is to use a Map and the observation that one needs N distinct pairs such that one element is double that of another element. Follow the steps below to solve the problem:



  • Initialize a map < integer, integer >, say, count, to store the count of array elements.
  • Traverse the array arr[] and update the count of each element in the Map count.
  • Iterate over the map count and perform the following operations:
    • Initialize a variable, say want, to form a pair with the current element, say X, and assign want = X/2, if X is less than 0. Otherwise, assign want = 2*X.
    • Check if X is less than 0 and X is odd or the count of X is greater than the count of want, then print “No” as it is impossible to form the pair of remaining X with any other element of the array.
    • Otherwise, update the count of want in the Map count as count(want) – count(X).
  • After completing the above steps, print “Yes” as there exists any combination of elements that satisfy the given property.

Below is the implementation of the above approach:

C++




// cpp program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if it is possible
// to rearrange the array elements
// that satisfies the given conditions
string canReorderDoubled(vector<int> A)
{
   
    // Stores the count of elements
    map<int,int> count;
 
    // Update the hash table
    for (int a : A)
        count[a]++;
 
    // Traverse the hash table
    for (auto x : count) {
 
        // If the count of current
        // element is zero
        if (x.second == 0)
            continue;
 
        // Stores the element needed
        // to form a pair with the
        // current element
        int xx = x.first;
        int want = xx < 0 ? xx / 2 : xx * 2;
 
        // If x is less than zero and odd
        if (xx < 0 && xx % 2 != 0)
            return "No";
 
        // If count of x is greater
        // than count of want
        if (x.second
            > count[want])
            return "No";
 
        // Update the count of want
        // in the hash table
        count[want] -= x.second;
    }
 
    // Return true if none of the
    // above cases satisfies
    return "Yes";
}
 
// Driver Code
int main()
{
 
    vector<int> arr = { 4, -2, 2, -4 };
    int N = 2;
 
    string res = canReorderDoubled(arr);
 
    // Print the result obtained
    cout<<(res);
}
 
// This code is contributed by mohit kumar 29.

Java




// Java program of the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to check if it is possible
    // to rearrange the array elements
    // that satisfies the given conditions
    public static String canReorderDoubled(int[] A)
    {
        // Stores the count of elements
        Map<Integer, Integer> count
            = new TreeMap<>();
 
        // Update the hash table
        for (int a : A)
            count.put(
                a, count.getOrDefault(a, 0) + 1);
 
        // Traverse the hash table
        for (int x : count.keySet()) {
 
            // If the count of current
            // element is zero
            if (count.get(x) == 0)
                continue;
 
            // Stores the element needed
            // to form a pair with the
            // current element
            int want = x < 0 ? x / 2 : x * 2;
 
            // If x is less than zero and odd
            if (x < 0 && x % 2 != 0)
                return "No";
 
            // If count of x is greater
            // than count of want
            if (count.get(x)
                > count.getOrDefault(want, 0))
                return "No";
 
            // Update the count of want
            // in the hash table
            count.put(want,
                      count.get(want)
                          - count.get(x));
        }
 
        // Return true if none of the
        // above cases satisfies
        return "Yes";
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int[] arr = { 4, -2, 2, -4 };
        int N = 2;
 
        String res = canReorderDoubled(arr);
 
        // Print the result obtained
        System.out.println(res);
    }
}

Python3




# Python 3 program of the above approach
 
# Function to check if it is possible
# to rearrange the array elements
# that satisfies the given conditions
 
def canReorderDoubled(A):
    # Stores the count of elements
    count = {}
 
    # Update the hash table
    for a in A:
        if a in count:
            count[a] += 1
        else:
            count[a] = 1
 
    # Traverse the hash table
    for key,value in count.items():
        # If the count of current
        # element is zero
        if (value == 0):
            continue
 
        # Stores the element needed
        # to form a pair with the
        # current element
        xx = key
        if xx < 0:
            want = xx / 2
        else:
            want = xx * 2
 
        # If x is less than zero and odd
        if (xx < 0 and xx % 2 != 0):
            return "No"
 
        # If count of x is greater
        # than count of want
        if (want in count and value > count[want]):
            return "No"
 
        # Update the count of want
        # in the hash table
        if want in count:
          count[want] -= value
 
    # Return true if none of the
    # above cases satisfies
    return "Yes"
 
# Driver Code
if __name__ == '__main__':
    arr =  [4, -2, 2, -4]
    N = 2
 
    res = canReorderDoubled(arr)
 
    # Print the result obtained
    print(res)
 
    # This code is contributed by bgangwar59.

Javascript




<script>
 
// Javascript program of the above approach
 
// Function to check if it is possible
// to rearrange the array elements
// that satisfies the given conditions
function canReorderDoubled(A)
{
   
    // Stores the count of elements
    var count= new Map();
 
    // Update the hash table
    A.forEach(a => {
        if(count.has(a))
            count.set(a, count.get(a)+1)
        else
            count.set(a, 1)
    });
 
    // Traverse the hash table
    count.forEach((value, key) => {
         
 
        // If the count of current
        // element is zero
        if (value != 0)
        {
 
            // Stores the element needed
            // to form a pair with the
            // current element
            var xx = key;
                var want = xx < 0 ? xx / 2 : xx * 2;
 
            // If x is less than zero and odd
            if (xx < 0 && xx % 2 != 0)
                    return "No";
 
            // If count of x is greater
            // than count of want
            if (value
                > count.get(want))
                return "No";
 
            // Update the count of want
            // in the hash table
            if(count.has(want))
                    count.set(want, count.get(want)-value)
        }
 
    });
 
    // Return true if none of the
    // above cases satisfies
    return "Yes";
}
 
// Driver Code
var arr = [4, -2, 2, -4];
var N = 2;
var res = canReorderDoubled(arr);
// Print the result obtained
document.write(res);
 
 
</script>
Output: 
Yes

 

Time Complexity: O(N*log N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :