Replace Non-Coprime Numbers in Array — LeetCode 2197 Python Solution

HardStackArrayMathNumber Theory
Problem
#2197
Pattern
Stack
Reading time
3 min

The problem

You are given an array of integers nums. Perform the following steps: Find any two adjacent numbers in nums that are non-coprime.

Example

Input
nums = [6,4,3,2,7,6,2]
Output
[12,7,6]
Explanation
- (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2].

Python solution

Python
class Solution:
    def replaceNonCoprimes(self, nums: List[int]) -> List[int]:
        stk = []
        for x in nums:
            stk.append(x)
            while len(stk) > 1:
                x, y = stk[-2:]
                g = gcd(x, y)
                if g == 1:
                    break
                stk.pop()
                stk[-1] = x * y // g
        return stk

Complexity

MeasureComplexity
TimeO(n \times \log M)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2197. Replace Non-Coprime Numbers in Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2197. Replace Non-Coprime Numbers in Array?
LeetCode 2197. Replace Non-Coprime Numbers in Array is rated Hard on LeetCode.
What is the time complexity of LeetCode 2197. Replace Non-Coprime Numbers in Array?
The Python solution on this page runs in O(n \times \log M).
What is the space complexity of LeetCode 2197. Replace Non-Coprime Numbers in Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2197. Replace Non-Coprime Numbers in Array cover?
LeetCode 2197. Replace Non-Coprime Numbers in Array is tagged Stack, Array, Math and Number Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview