Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if an array of pairs can be sorted by swapping pairs with different first elements
Next article icon

Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array

Last Updated : 04 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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++
// 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
// 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
# 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#
// 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  
JavaScript
<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:

  • Initialize two variables, say left and right, with the value 0.
  • Traverse the array from left to right and do the following:
  • a. If the current element arr[i] is greater than the next element arr[i+1], set left to i.
  • Traverse the array from right to left and do the following:
  • a. If the current element arr[i] is less than the previous element arr[i-1], set right to i.
  • If either left or right is still 0, then the array is already sorted and can be swapped using adjacent elements.
  • Otherwise, swap arr[left] with arr[right] and check if the resulting array is sorted.
  • If the array is sorted, return "Yes", otherwise return "No".
     

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

C++
#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; } 
Java
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));     } } 
Python3
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)) 
C#
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));     } } 
JavaScript
// 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)


Next Article
Check if an array of pairs can be sorted by swapping pairs with different first elements
author
__mahakal
Improve
Article Tags :
  • Misc
  • Searching
  • Sorting
  • Mathematical
  • DSA
  • Arrays
  • array-rearrange
Practice Tags :
  • Arrays
  • Mathematical
  • Misc
  • Searching
  • Sorting

Similar Reads

  • Check if array can be sorted by swapping pairs with GCD of set bits count equal to that of the smallest array element
    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
    9 min read
  • Rearrange array to make it non-decreasing by swapping pairs having GCD equal to minimum array element
    Given an array, arr[] consisting of N positive integers, the task is to make the array non-decreasing by swapping pairs (arr[i], arr[j]) such that i != j (1 ≤ i, j ≤ n) and GCD(arr[i], arr[j]) is equal to the minimum element present in the array. Examples: Input: arr[] = {4, 3, 6, 6, 2, 9}Output: Ye
    6 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
  • Count pairs from an array having GCD equal to the minimum element in the pair
    Given an array arr[] consisting of N integers, the task is to find the number of pairs such that the GCD of any pair of array elements is the minimum element of that pair. Examples: Input: arr[ ] = {2, 3, 1, 2}Output: 4Explanation:Below are the all possible pairs from the given array: (0, 1): The GC
    14 min read
  • Check if Array can be sorted by swapping adjacent elements having odd sum
    Given an array arr[], the task is to check if the array can be sorted using the given operation any number of times. In one operation, you can swap any two adjacent elements if their sum is odd. Examples: Input: arr[] = [1, 6, 31, 14]Output: YesExplanation: Swap 31 and 14 (31 + 14 = 45 which is odd)
    7 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 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
  • Check if it is possible to sort the array without swapping adjacent elements
    Given an array arr[] of size N, check if it is possible to sort arr[] without swapping adjacent elements. In other words, check if it is possible to sort arr[] by swapping elements but swapping two consecutive element is not allowed. Examples: Input: N = 4, arr[] = {2, 3, 1, 4}Output: YESExplanation
    5 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 an array can be sorted by swapping adjacent elements such that each element is swapped even number of times
    Given an array arr[] consisting of N integers, the task is to check if the array can be sorted by swapping adjacent elements any number of times such that each array element is swapped even a number of times. Examples: Input: arr[] = {4, 3, 2, 5}Output: YesExplanation:Below are the possible order of
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences