Open In App

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, 2, 9} 
Output: Yes 
Explanation: 
Smallest element in the array = 2 
Swap arr[0] and arr[2], since they have gcd equal to 2. Therefore, arr[] = {6, 3, 4, 6, 2, 9} 
Swap arr[0] and arr[4], since they have gcd equal to 2. Therefore, arr[] = {2, 3, 4, 6, 6, 9} 
 Input: arr[] = {2, 6, 2, 4, 5} 
Output: No 

Approach: The idea is to find the smallest element from the array and check if it is possible to sort the array. Below are the steps: 

  1. Find the smallest element of the array and store it in a variable, say mn.
  2. Store the array in a temporary array, say B[].
  3. Sort the original array arr[].
  4. Now, iterate over the array, if there is an element which is not divisible by mn and whose position is changed after sorting, then print “NO”. Otherwise, rearrange the elements divisible by mn by swapping it with other elements.
  5. If the position of all elements which are not divisible by mn remains unchanged, then print “YES”.

Below is the implementation of the above approach: 




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if it is
// possible to sort array or not
void isPossible(int arr[], int N)
{
 
    // Store the smallest element
    int mn = INT_MAX;
 
    // Copy the original array
    int B[N];
 
    // Iterate over the given array
    for (int i = 0; i < N; i++) {
 
        // Update smallest element
        mn = min(mn, arr[i]);
 
        // Copy elements of arr[]
        // to array B[]
        B[i] = arr[i];
    }
 
    // Sort original array
    sort(arr, arr + N);
 
    // Iterate over the given array
    for (int i = 0; i < N; i++) {
 
        // If the i-th element is not
        // in its sorted place
        if (arr[i] != B[i]) {
 
            // Not possible to swap
            if (B[i] % mn != 0) {
                cout << "No";
                return;
            }
        }
    }
 
    cout << "Yes";
    return;
}
 
// Driver Code
int main()
{
    // Given array
    int N = 6;
    int arr[] = { 4, 3, 6, 6, 2, 9 };
 
    // Function Call
    isPossible(arr, N);
 
    return 0;
}




// Java implementation of
// the above approach
import java.util.*;
class GFG{
 
// Function to check if it is
// possible to sort array or not
static void isPossible(int arr[],
                       int N)
{
  // Store the smallest element
  int mn = Integer.MAX_VALUE;
 
  // Copy the original array
  int []B = new int[N];
 
  // Iterate over the given array
  for (int i = 0; i < N; i++)
  {
    // Update smallest element
    mn = Math.min(mn, arr[i]);
 
    // Copy elements of arr[]
    // to array B[]
    B[i] = arr[i];
  }
 
  // Sort original array
  Arrays.sort(arr);
 
  // Iterate over the given array
  for (int i = 0; i < N; i++)
  {
    // If the i-th element is not
    // in its sorted place
    if (arr[i] != B[i])
    {
      // Not possible to swap
      if (B[i] % mn != 0)
      {
        System.out.print("No");
        return;
      }
    }
  }
  System.out.print("Yes");
  return;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array
  int N = 6;
  int arr[] = {4, 3, 6, 6, 2, 9};
 
  // Function Call
  isPossible(arr, N);
}
}
 
// This code is contributed by 29AjayKumar




# Python3 implementation of
# the above approach
import sys
 
# Function to check if it is
# possible to sort array or not
def isPossible(arr, N):
   
    # Store the smallest element
    mn = sys.maxsize;
 
    # Copy the original array
    B = [0] * N;
 
    # Iterate over the given array
    for i in range(N):
       
        # Update smallest element
        mn = min(mn, arr[i]);
 
        # Copy elements of arr
        # to array B
        B[i] = arr[i];
 
    # Sort original array
    arr.sort();
 
    # Iterate over the given array
    for i in range(N):
       
        # If the i-th element is not
        # in its sorted place
        if (arr[i] != B[i]):
           
            # Not possible to swap
            if (B[i] % mn != 0):
                print("No");
                return;
 
    print("Yes");
    return;
 
# Driver Code
if __name__ == '__main__':
   
    # Given array
    N = 6;
    arr = [4, 3, 6, 6, 2, 9];
 
    # Function Call
    isPossible(arr, N);
 
# This code is contributed by 29AjayKumar




// C# implementation of
// the above approach
using System;
class GFG{
 
// Function to check if it is
// possible to sort array or not
static void isPossible(int []arr,
                       int N)
{
  // Store the smallest element
  int mn = int.MaxValue;
 
  // Copy the original array
  int []B = new int[N];
 
  // Iterate over the given array
  for (int i = 0; i < N; i++)
  {
    // Update smallest element
    mn = Math.Min(mn, arr[i]);
 
    // Copy elements of []arr
    // to array []B
    B[i] = arr[i];
  }
 
  // Sort original array
  Array.Sort(arr);
 
  // Iterate over the given array
  for (int i = 0; i < N; i++)
  {
    // If the i-th element is not
    // in its sorted place
    if (arr[i] != B[i])
    {
      // Not possible to swap
      if (B[i] % mn != 0)
      {
        Console.Write("No");
        return;
      }
    }
  }
  Console.Write("Yes");
  return;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array
  int N = 6;
  int []arr = {4, 3, 6, 6, 2, 9};
 
  // Function Call
  isPossible(arr, N);
}
}
 
// This code is contributed by Rajput-Ji




<script>
 
// JavaScript program for
// the above approach
 
// Function to check if it is
// possible to sort array or not
function isPossible(arr,
                       N)
{
  // Store the smallest element
  let mn = Number.MAX_VALUE;
  
  // Copy the original array
  let B = [];
  
  // Iterate over the given array
  for (let i = 0; i < N; i++)
  {
    // Update smallest element
    mn = Math.min(mn, arr[i]);
  
    // Copy elements of arr[]
    // to array B[]
    B[i] = arr[i];
  }
  
  // Sort original array
  arr.sort();
  
  // Iterate over the given array
  for (let i = 0; i < N; i++)
  {
    // If the i-th element is not
    // in its sorted place
    if (arr[i] != B[i])
    {
      // Not possible to swap
      if (B[i] % mn != 0)
      {
        document.write("No");
        return;
      }
    }
  }
  document.write("Yes");
  return;
}
 
 
// Driver code
 
  // Given array
  let N = 6;
  let arr = [4, 3, 6, 6, 2, 9];
  
  // Function Call
  isPossible(arr, N);
                             
</script>

Output
Yes



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

Approach 2:

Here’s another approach to check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array:

Here’s the C++ code for the above approach:




#include <bits/stdc++.h>
using namespace std;
 
// Function to check if an array can be sorted
// by swapping adjacent elements
string isPossible(int arr[], int n)
{
    int left = 0, right = 0;
 
    // Find the left index where the array is not sorted
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] > arr[i+1]) {
            left = i;
            break;
        }
    }
 
    // If array is already sorted
    if (left == 0) {
        return "Yes";
    }
 
    // Find the right index where the array is not sorted
    for (int i = n - 1; i >= left; i--) {
        if (arr[i] < arr[i-1]) {
            right = i;
            break;
        }
    }
 
    // Swap adjacent elements
    swap(arr[left], arr[right]);
 
    // Check if array is sorted
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] > arr[i+1]) {
            return "No";
        }
    }
 
    return "Yes";
}
 
// Driver code
int main()
{
    int arr[] = {4, 2, 3, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    cout << isPossible(arr, n);
 
    return 0;
}




public class GFG {
    // Function to check if an array can be sorted
    // by swapping adjacent elements
    public static String isPossible(int[] arr) {
        int n = arr.length;
        int left = 0, right = 0;
 
        // Find the left index where the array is not sorted
        for (int i = 0; i < n - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                left = i;
                break;
            }
        }
 
        // If the array is already sorted
        if (left == 0) {
            return "Yes";
        }
 
        // Find the right index where the array is not sorted
        for (int i = n - 1; i >= left; i--) {
            if (arr[i] < arr[i - 1]) {
                right = i;
                break;
            }
        }
 
        // Swap adjacent elements
        int temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
 
        // Check if the array is sorted
        for (int i = 0; i < n - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                return "No";
            }
        }
 
        return "Yes";
    }
 
    public static void main(String[] args) {
        int[] arr = {4, 2, 3, 1};
 
        // Function Call
        System.out.println(isPossible(arr));
    }
}




def isPossible(arr, n):
    left = 0
    right = 0
 
    # Find the left index where the array is not sorted
    for i in range(n - 1):
        if arr[i] > arr[i + 1]:
            left = i
            break
 
    # If array is already sorted
    if left == 0:
        return "Yes"
 
    # Find the right index where the array is not sorted
    for i in range(n - 1, left, -1):
        if arr[i] < arr[i - 1]:
            right = i
            break
 
    # Swap adjacent elements
    arr[left], arr[right] = arr[right], arr[left]
 
    # Check if array is sorted
    for i in range(n - 1):
        if arr[i] > arr[i + 1]:
            return "No"
 
    return "Yes"
 
 
# Driver code
arr = [4, 2, 3, 1]
n = len(arr)
 
print(isPossible(arr, n))




using System;
 
class Program
{
    // Function to check if an array can be sorted
    // by swapping adjacent elements
    static string IsPossible(int[] arr)
    {
        int n = arr.Length;
        int left = 0, right = 0;
 
        // Find the left index where the array is not sorted
        for (int i = 0; i < n - 1; i++)
        {
            if (arr[i] > arr[i + 1])
            {
                left = i;
                break;
            }
        }
 
        // If array is already sorted
        if (left == 0)
        {
            return "Yes";
        }
 
        // Find the right index where the array is not sorted
        for (int i = n - 1; i >= left; i--)
        {
            if (arr[i] < arr[i - 1])
            {
                right = i;
                break;
            }
        }
 
        // Swap adjacent elements
        int temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
 
        // Check if array is sorted
        for (int i = 0; i < n - 1; i++)
        {
            if (arr[i] > arr[i + 1])
            {
                return "No";
            }
        }
 
        return "Yes";
    }
 
    // Driver code
    static void Main()
    {
        int[] arr = { 4, 2, 3, 1 };
 
        Console.WriteLine(IsPossible(arr));
    }
}




// Function to check if an array can be sorted
// by swapping adjacent elements
function isPossible(arr, n) {
    let left = 0,
        right = 0;
 
    // Find the left index where the array is not sorted
    for (let i = 0; i < n - 1; i++) {
        if (arr[i] > arr[i + 1]) {
            left = i;
            break;
        }
    }
 
    // If array is already sorted
    if (left == 0) {
        return "Yes";
    }
 
    // Find the right index where the array is not sorted
    for (let i = n - 1; i >= left; i--) {
        if (arr[i] < arr[i - 1]) {
            right = i;
            break;
        }
    }
 
    // Swap adjacent elements
    [arr[left], arr[right]] = [arr[right], arr[left]];
 
    // Check if array is sorted
    for (let i = 0; i < n - 1; i++) {
        if (arr[i] > arr[i + 1]) {
            return "No";
        }
    }
 
    return "Yes";
}
 
let arr = [4, 2, 3, 1];
let n = arr.length;
 
console.log(isPossible(arr, n));

Output
Yes



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


Article Tags :