Open In App

Check if array can be sorted by swapping pairs with GCD of set bits count equal to that of the smallest array element

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers, the task is to check if it is possible to sort the array using the following swap operations:

Swapping of two numbers is valid only if the Greatest Common Divisor of count of set bits of the two numbers is equal to the number of set bits in the smallest element of the array. 
 

If it is possible to sort the array by performing only the above swaps, then print “Yes”. Otherwise, print “No”.

Examples:

Input: arr[] = {2, 3, 5, 7, 6} 
Output: Yes 
Explanation: 
7 and 6 are needed to be swapped to make the array sorted. 
7 has 3 set bits and 6 has 2 set bits. 
Since GCD(2, 3) = 1, which is equal to the number of set bits in the smallest integer from the array i.e., 2 (1 set bit). 
Therefore, the array can be sorted by swapping (7, 6).

Input: arr[] = {3, 3, 15, 7} 
Output: No 
Explanation: 
15 and 7 are needed to be swapped to make the array sorted. 
15 has 4 set bits and 7 has 3 set bits. GCD(4, 3) = 1, which is not equal to the number of set bits in the smallest integer from the array i.e., 3(2 set bit). 
Therefore, the array cannot be sorted. 

Approach: Follow the steps below to solve the problem:

  1. Sort the given array and store it in an auxiliary array(say dup[]).
  2. Iterate over the array and for every element, check if it is at the same index in both arr[] and dup[] or not. If found to be true, proceed to the next index.
  3. Otherwise, if swapping of ith and jth position elements is required in arr[] then calculate the GCD of set bits of arr[i] with set bits of arr[j] and check if it is equal to the count of set bits in the smallest element of the array or not.
  4. If any such swapping is not allowed, print “No”. Otherwise, print “Yes”.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count number of set
// bits in an integer
int calculateSetBit(int n)
{
    int count = 0;
 
    // Traverse every bits
    for (int i = 0; i < 32; i++) {
        if (n & 1)
            count++;
 
        // Right shift by 1
        n = n >> 1;
    }
 
    return count;
}
 
// Function to check if sorting the
// given array is possible or not
void sortPossible(int arr[], int n)
{
    // Duplicate array
    int dup[n];
 
    for (int i = 0; i < n; i++)
        dup[i] = arr[i];
 
    // Sorted array to check if the
    // original array can be sorted
    sort(dup, dup + n);
 
    // Flag variable to check
    // if possible to sort
    bool flag = 1;
 
    // Calculate bits of smallest
    // array element
    int bit = calculateSetBit(dup[0]);
 
    // Check every wrong placed
    // integer in the array
    for (int i = 0; i < n; i++) {
        if (arr[i] != dup[i]) {
 
            // Swapping only if GCD of set
            // bits is equal to set bits in
            // smallest integer
            if (__gcd(
                    calculateSetBit(arr[i]),
                    bit)
                != bit) {
                flag = 0;
                break;
            }
        }
    }
 
    // Print the result
    if (flag) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
 
    return;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 9, 12, 6 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    sortPossible(arr, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
  
// Recursive function to return
// gcd of a and b
static int gcd(int a, int b)
{
     
    // Everything divides 0 
    if (a == 0)
        return b;
    if (b == 0)
         return a;
        
    // Base case
    if (a == b)
        return a;
        
    // a is greater
    if (a > b)
        return gcd(a - b, b);
    return gcd(a, b - a);
}
     
// Function to count number of set
// bits in an integer
static int calculateSetBit(int n)
{
    int count = 0;
  
    // Traverse every bits
    for(int i = 0; i < 32; i++)
    {
        if ((n & 1) != 0)
            count++;
  
        // Right shift by 1
        n = n >> 1;
    }
    return count;
}
  
// Function to check if sorting the
// given array is possible or not
static void sortPossible(int arr[], int n)
{
     
    // Duplicate array
    int dup[] = new int[n];
  
    for(int i = 0; i < n; i++)
        dup[i] = arr[i];
  
    // Sorted array to check if the
    // original array can be sorted
    Arrays.sort(dup);
  
    // Flag variable to check
    // if possible to sort
    int flag = 1;
  
    // Calculate bits of smallest
    // array element
    int bit = calculateSetBit(dup[0]);
  
    // Check every wrong placed
    // integer in the array
    for(int i = 0; i < n; i++)
    {
        if (arr[i] != dup[i])
        {
             
            // Swapping only if GCD of set
            // bits is equal to set bits in
            // smallest integer
            if (gcd(calculateSetBit(
                arr[i]), bit) != bit)
            {
                flag = 0;
                break;
            }
        }
    }
  
    // Print the result
    if (flag != 0)
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
    return;
}
  
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 3, 9, 12, 6 };
  
    int N = arr.length;
  
    // Function call
    sortPossible(arr, N);
}
}
 
// This code is contributed by sanjoy_62


Python3




# Python3 program for the above approach
from math import gcd
 
# Function to count number of set
# bits in an eger
def calculateSetBit(n):
 
    count = 0
 
    # Traverse every bits
    for i in range(32):
        if (n & 1):
            count += 1
 
        # Right shift by 1
        n = n >> 1
         
    return count
 
# Function to check if sorting the
# given array is possible or not
def sortPossible(arr, n):
 
    # Duplicate array
    dup = [0] * n
 
    for i in range(n):
        dup[i] = arr[i]
 
    # Sorted array to check if the
    # original array can be sorted
    dup = sorted(dup)
 
    # Flag variable to check
    # if possible to sort
    flag = 1
 
    # Calculate bits of smallest
    # array element
    bit = calculateSetBit(dup[0])
 
    # Check every wrong placed
    # eger in the array
    for i in range(n):
        if (arr[i] != dup[i]):
 
            # Swapping only if GCD of set
            # bits is equal to set bits in
            # smallest eger
            if (gcd(calculateSetBit(arr[i]), bit) != bit):
                flag = 0
                break
 
    # Print the result
    if (flag):
        print("Yes")
    else:
        print("No")
 
    return
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 3, 9, 12, 6 ]
 
    N = len(arr)
 
    # Function call
    sortPossible(arr, N)
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach 
using System;
 
class GFG{
  
// Recursive function to return
// gcd of a and b
static int gcd(int a, int b)
{
     
    // Everything divides 0 
    if (a == 0)
        return b;
    if (b == 0)
         return a;
        
    // Base case
    if (a == b)
        return a;
        
    // a is greater
    if (a > b)
        return gcd(a - b, b);
    return gcd(a, b - a);
}
     
// Function to count number of set
// bits in an integer
static int calculateSetBit(int n)
{
    int count = 0;
  
    // Traverse every bits
    for(int i = 0; i < 32; i++)
    {
        if ((n & 1) != 0)
            count++;
  
        // Right shift by 1
        n = n >> 1;
    }
    return count;
}
  
// Function to check if sorting the
// given array is possible or not
static void sortPossible(int[] arr, int n)
{
     
    // Duplicate array
    int[] dup = new int[n];
  
    for(int i = 0; i < n; i++)
        dup[i] = arr[i];
  
    // Sorted array to check if the
    // original array can be sorted
    Array.Sort(dup);
  
    // Flag variable to check
    // if possible to sort
    int flag = 1;
  
    // Calculate bits of smallest
    // array element
    int bit = calculateSetBit(dup[0]);
  
    // Check every wrong placed
    // integer in the array
    for(int i = 0; i < n; i++)
    {
        if (arr[i] != dup[i])
        {
             
            // Swapping only if GCD of set
            // bits is equal to set bits in
            // smallest integer
            if (gcd(calculateSetBit(
                arr[i]), bit) != bit)
            {
                flag = 0;
                break;
            }
        }
    }
  
    // Print the result
    if (flag != 0)
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
  
    return;
}
  
// Driver Code
public static void Main()
{
    int[] arr = { 3, 9, 12, 6 };
  
    int N = arr.Length;
  
    // Function call
    sortPossible(arr, N);
}
}
 
// This code is contributed by sanjoy_62


Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Recursive function to return
// gcd of a and b
function gcd(a, b)
{
      
    // Everything divides 0
    if (a == 0)
        return b;
    if (b == 0)
         return a;
         
    // Base case
    if (a == b)
        return a;
         
    // a is greater
    if (a > b)
        return gcd(a - b, b);
    return gcd(a, b - a);
}
      
// Function to count number of set
// bits in an integer
function calculateSetBit(n)
{
    let count = 0;
   
    // Traverse every bits
    for(let i = 0; i < 32; i++)
    {
        if ((n & 1) != 0)
            count++;
   
        // Right shift by 1
        n = n >> 1;
    }
    return count;
}
   
// Function to check if sorting the
// given array is possible or not
function sortPossible(arr, n)
{
      
    // Duplicate array
    let dup = [];
   
    for(let i = 0; i < n; i++)
        dup[i] = arr[i];
   
    // Sorted array to check if the
    // original array can be sorted
    dup.sort();
   
    // Flag variable to check
    // if possible to sort
    let flag = 1;
   
    // Calculate bits of smallest
    // array element
    let bit = calculateSetBit(dup[0]);
   
    // Check every wrong placed
    // integer in the array
    for(let i = 0; i < n; i++)
    {
        if (arr[i] != dup[i])
        {
              
            // Swapping only if GCD of set
            // bits is equal to set bits in
            // smallest integer
            if (gcd(calculateSetBit(
                arr[i]), bit) != bit)
            {
                flag = 0;
                break;
            }
        }
    }
   
    // Print the result
    if (flag != 0)
    {
        document.write("Yes");
    }
    else
    {
        document.write("No");
    }
    return;
}
 
// Driver code
    let arr = [ 3, 9, 12, 6 ];
    let N = arr.length;
   
    // Function call
    sortPossible(arr, N);
      
     // This code is contributed by target_2.
</script>


Output: 

Yes

 

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



Last Updated : 01 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads