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

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.