-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path2197-replace-non-coprime-numbers-in-array.js
More file actions
48 lines (44 loc) · 1.36 KB
/
2197-replace-non-coprime-numbers-in-array.js
File metadata and controls
48 lines (44 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 2197. Replace Non-Coprime Numbers in Array
* https://leetcode.com/problems/replace-non-coprime-numbers-in-array/
* Difficulty: Hard
*
* 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.
*/
/**
* @param {number[]} nums
* @return {number[]}
*/
var replaceNonCoprimes = function(nums) {
const result = [];
for (let num of nums) {
while (result.length > 0) {
const last = result[result.length - 1];
const gcdValue = gcd(last, num);
if (gcdValue === 1) break;
result.pop();
num = (last / gcdValue) * num;
}
result.push(num);
}
return result;
};
function gcd(a, b) {
while (b) {
[a, b] = [b, a % b];
}
return a;
}