#2197

Replace Non-Coprime Numbers in Array

Hard
ArrayMathStackNumber TheoryStackArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a stack to efficiently manage the merging of adjacent non-coprime numbers. By processing the array in a single pass and using the stack to keep track of the current state, we can achieve better performance.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty stack.
  2. 2Step 2: Iterate through each number in the array.
  3. 3Step 3: For each number, check if it can be merged with the top of the stack (if the stack is not empty). If they are non-coprime, replace them with their LCM.
  4. 4Step 4: If they are coprime, push the current number onto the stack.
  5. 5Step 5: Continue until all numbers are processed, then return the stack as the final result.
solution.py13 lines
1# Full working Python code
2import math
3
4def replaceNonCoprime(nums):
5    stack = []
6    for num in nums:
7        while stack and math.gcd(stack[-1], num) > 1:
8            num = stack.pop() * num // math.gcd(stack[-1], num)
9        stack.append(num)
10    return stack
11
12# Example usage
13print(replaceNonCoprime([6,4,3,2,7,6,2]))

Complexity note: The time complexity is O(n) because we make a single pass through the array, and each number is pushed and popped from the stack at most once. The space complexity is O(n) due to the stack storing the results.

  • 1Adjacent numbers can be merged if they share common factors.
  • 2Using a stack allows for efficient merging and backtracking.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.