Skip to content

2197. Replace Non-Coprime Numbers in Array 👍

  • Time: $O(n\log 10^8)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  vector<int> replaceNonCoprimes(vector<int>& nums) {
    vector<int> ans;

    for (int num : nums) {
      while (!ans.empty() && std::gcd(ans.back(), num) > 1)
        num = std::lcm(ans.back(), num), ans.pop_back();
      ans.push_back(num);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public List<Integer> replaceNonCoprimes(int[] nums) {
    LinkedList<Integer> ans = new LinkedList<>();

    for (int num : nums) {
      while (!ans.isEmpty() && gcd(ans.getLast(), num) > 1)
        num = lcm(ans.removeLast(), num);
      ans.addLast(num);
    }

    return ans;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }

  private int lcm(int a, int b) {
    return a * (b / gcd(a, b));
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def replaceNonCoprimes(self, nums: list[int]) -> list[int]:
    ans = []

    for num in nums:
      while ans and math.gcd(ans[-1], num) > 1:
        num = math.lcm(ans.pop(), num)
      ans.append(num)

    return ans