Replace Non-Coprime Numbers in Array - Problem
You are given an array of integers nums. Perform the following steps:
- Find any two adjacent numbers in
numsthat 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.
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.
Input & Output
Example 1 — Basic Merging
$
Input:
nums = [6,4,3,2,21]
›
Output:
[6,252]
💡 Note:
Step by step: [6,4,3,2,21] → GCD(4,3)=1, GCD(3,2)=1, GCD(2,21)=1, no adjacent non-coprime pairs initially. However, after processing with stack: 4 and 3 can merge through cascading with later elements, resulting in [6,252].
Example 2 — Simple Case
$
Input:
nums = [2,3,4]
›
Output:
[2,3,4]
💡 Note:
GCD(2,3)=1 and GCD(3,4)=1, all pairs are coprime, so no merging occurs. Return original array.
Example 3 — Complete Merge
$
Input:
nums = [4,6,15,35]
›
Output:
[420]
💡 Note:
GCD(6,15)=3>1, merge to get [4,30,35]. Then GCD(4,30)=2>1, merge to get [60,35]. Finally GCD(60,35)=5>1, merge to get [420].
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
- The final array values are ≤ 108
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Original array with potential non-coprime adjacent pairs
2
Find & Merge
Identify GCD > 1 pairs and replace with LCM
3
Final Result
Array with no adjacent non-coprime pairs
Key Takeaway
🎯 Key Insight: Use a stack to efficiently handle cascading merges when processing non-coprime adjacent pairs
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code