2025-09-16 15:41:40 +0000 UTC

Replace Non-Coprime Numbers in Array

Code

from math import gcd

class Solution(object):
    def replaceNonCoprimes(self, nums):
        stack = []

        for num in nums:
            while stack:
                g = gcd(stack[-1], num)
                if g == 1:
                    break
                num = (stack.pop() * num) // g
            stack.append(num)

        return stack