[LeetCode] Replace Non-Coprime Numbers in Array

2197. Replace Non-Coprime Numbers in Array

You are given an array of integers nums. Perform the following steps:

  1. Find any two adjacent numbers in nums that are non-coprime.
  2. If no such numbers are found, stop the process.
  3. Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple).
  4. Repeat this process as long as you keep finding two adjacent non-coprime numbers.

Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result.

The test cases are generated such that the values in the final array are less than or equal to 108.

Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<int> replaceNonCoprimes(vector<int>& nums) {
vector<int> res;
for(int i = 0; i < nums.size(); i++) {
res.push_back(nums[i]);
while(res.size() >= 2) {
int sz = res.size();
int g = __gcd(res[sz - 1], res[sz - 2]);
if(g <= 1) break;
else {
int num = res[sz - 1] / g * res[sz - 2];
res.pop_back();
res.pop_back();
res.push_back(num);
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/06/PS/LeetCode/replace-non-coprime-numbers-in-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.