Rearrange array to make it non-decreasing by swapping elements with equal GCD

By | September 29, 2023

Given an array (with all elements greater than 0), create a non-decreasing array by swapping 2 elements if their gcd(Greatest Common Factor) is equal to the minimum element of the array.
You have to print “YES” if this is possible, and if not print “NO”.

Examples:

Input:
a[] = {6,2,4,8,12}
Output: YES
Explaination:
Swap a[1] and a[2] and then swap a[0] and a[2]

Input:
a[] = {1,2,3,4,5}
Output: YES
Explaination: 
Array is already sorted

Approach:

  1. Find the minimum of array a[] say min.
  2. Find all the elements which is not at their position and check that it is divisible by min or not.
  3. If all elements which is not at its position is divisible by min print “YES “else “NO”.

Implementation in C++:

#include<bits/stdc++.h>

using namespace std;

int main() {
  int n, i, min, flag = 0;
  cin >> n;
  int a[n], b[n];
  for (i = 0; i < n; i++) {
    cin >> a[i];
    b[i] = a[i];
  }
  sort(b, b + n);
  min = b[0];
  for (i = 0; i < n; i++) {
    if (a[i] != b[i]) {
      if (b[i] % min != 0) {
        flag = 1;
        break;
      }
    }
  }
  if (flag == 1)
    cout << "NO" << endl;
  else {
    cout << "YES" << endl;
  }
}

Input:

6,2,4,8,12

Output:

YES 

Time complexity: O(n)

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.