Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an array of integers nums. Perform the following steps:
nums that are non-coprime.Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result.
The test cases are generated such that the values in the final array are less than or equal to 108.
Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.
Example 1:
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]. - (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2]. - (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2]. - (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6]. There are no more adjacent non-coprime numbers in nums. Thus, the final modified array is [12,7,6]. Note that there are other ways to obtain the same resultant array.
Example 2:
Input: nums = [2,2,1,1,3,3,3] Output: [2,1,1,3] Explanation: - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3]. - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3]. - (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3]. There are no more adjacent non-coprime numbers in nums. Thus, the final modified array is [2,1,1,3]. Note that there are other ways to obtain the same resultant array.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 105108.Problem summary: You are given an array of integers nums. Perform the following steps: Find any two adjacent numbers in nums that are non-coprime. If no such numbers are found, stop the process. Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple). Repeat this process as long as you keep finding two adjacent non-coprime numbers. Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Stack
[6,4,3,2,7,6,2]
[2,2,1,1,3,3,3]
remove-all-adjacent-duplicates-in-string-ii)number-of-pairs-of-interchangeable-rectangles)split-the-array-to-make-coprime-products)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2197: Replace Non-Coprime Numbers in Array
class Solution {
public List<Integer> replaceNonCoprimes(int[] nums) {
List<Integer> stk = new ArrayList<>();
for (int x : nums) {
stk.add(x);
while (stk.size() > 1) {
x = stk.get(stk.size() - 1);
int y = stk.get(stk.size() - 2);
int g = gcd(x, y);
if (g == 1) {
break;
}
stk.remove(stk.size() - 1);
stk.set(stk.size() - 1, (int) ((long) x * y / g));
}
}
return stk;
}
private int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
}
// Accepted solution for LeetCode #2197: Replace Non-Coprime Numbers in Array
func replaceNonCoprimes(nums []int) []int {
stk := []int{}
for _, x := range nums {
stk = append(stk, x)
for len(stk) > 1 {
x = stk[len(stk)-1]
y := stk[len(stk)-2]
g := gcd(x, y)
if g == 1 {
break
}
stk = stk[:len(stk)-1]
stk[len(stk)-1] = x * y / g
}
}
return stk
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
# Accepted solution for LeetCode #2197: Replace Non-Coprime Numbers in Array
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
// Accepted solution for LeetCode #2197: Replace Non-Coprime Numbers in Array
impl Solution {
pub fn replace_non_coprimes(nums: Vec<i32>) -> Vec<i32> {
fn gcd(mut a: i64, mut b: i64) -> i64 {
while b != 0 {
let t = a % b;
a = b;
b = t;
}
a
}
let mut stk: Vec<i64> = Vec::new();
for x in nums {
stk.push(x as i64);
while stk.len() > 1 {
let x = *stk.last().unwrap();
let y = stk[stk.len() - 2];
let g = gcd(x, y);
if g == 1 {
break;
}
stk.pop();
let last = stk.last_mut().unwrap();
*last = x / g * y;
}
}
stk.into_iter().map(|v| v as i32).collect()
}
}
// Accepted solution for LeetCode #2197: Replace Non-Coprime Numbers in Array
function replaceNonCoprimes(nums: number[]): number[] {
const gcd = (a: number, b: number): number => {
if (b === 0) {
return a;
}
return gcd(b, a % b);
};
const stk: number[] = [];
for (let x of nums) {
stk.push(x);
while (stk.length > 1) {
x = stk.at(-1)!;
const y = stk.at(-2)!;
const g = gcd(x, y);
if (g === 1) {
break;
}
stk.pop();
stk.pop();
stk.push(((x * y) / g) | 0);
}
}
return stk;
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.