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 :
01 Oct, 2021
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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read