Skip to content

Commit a9765ac

Browse files
authored
Create 2197-replace-non-coprime-numbers-in-array.js
1 parent a14e99f commit a9765ac

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const gcd = (a, b) => (b == 0 ? a : gcd(b, a % b));
2+
/**
3+
* @param {number[]} nums
4+
* @return {number[]}
5+
*/
6+
const replaceNonCoprimes = function (nums) {
7+
const stk = [];
8+
for (let x of nums) {
9+
if (stk.length === 0) {
10+
stk.push(x);
11+
} else {
12+
while (stk.length && gcd(stk[stk.length - 1], x) !== 1) {
13+
// check if it can be merged with the value to its left
14+
const last = stk.pop(),
15+
g = gcd(x, last);
16+
x = (x / g) * last; // merge value, update lcm to x
17+
}
18+
stk.push(x);
19+
}
20+
}
21+
return stk;
22+
};

0 commit comments

Comments
 (0)