Check if array can be sorted by swapping pairs with GCD of set bits count equal to that of the smallest array element
Last Updated :
15 Jul, 2025
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:
- Sort the given array and store it in an auxiliary array(say dup[]).
- 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.
- 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.
- 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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array Given an array arr[] of size N, the task is to check if an array can be sorted by swapping only the elements whose GCD (greatest common divisor) is equal to the smallest element of the array. Print âYesâ if it is possible to sort the array. Otherwise, print âNoâ. Examples: Input: arr[] = {4, 3, 6, 6
11 min read
Check if an array of pairs can be sorted by swapping pairs with different first elements Given an array arr[] consisting of N pairs, where each pair represents the value and ID respectively, the task is to check if it is possible to sort the array by the first element by swapping only pairs having different IDs. If it is possible to sort, then print "Yes". Otherwise, print "No". Example
11 min read
Check if an Array can be converted to other by replacing pairs with GCD Given arrays A[] and B[] each of length N and A[i] has all the elements from 1 to N, the task is to check if it is possible to convert A[] to B[] by replacing any pair of A[] with their GCD. Examples: Input: N = 2, A[] = {1, 2}, B[] = {1, 1}Output: YES Explanation:First Operation - For A[], choose i
15 min read
Check if array can be sorted by swapping adjacent elements of opposite parity Given an array A of size n, the task is to check if the array can be sorted in increasing order, if the only operation allowed is swapping the adjacent elements if they are of opposite parity. The operation can be done any number of times. Examples: Input : n = 4, A = [1, 6, 51, 16]Output: YESExplan
9 min read
Check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array Given an array A[] of size N and a binary array B[] of size N, the task is to check if the array A[] can be converted into a sorted array by swapping pairs (A[i], A[j]) if B[i] is not equal to B[j]. If the array A[] can be sorted, then print "Yes". Otherwise, print "No". Examples: Input: A[] = {3, 1
15 min read
Check if the array can be sorted only if the elements on given positions can be swapped Given an array arr[] of length N and another array P[] containing {a1, a2, ... ak} which represents the positions of the given array arr[], the task is to check if the array can be sorted by only swapping the elements' arr[ai], arr[ai+1] where 'i' is some element in the array P[].Examples: Input: ar
8 min read