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:
[84]
💡 Note:
Using stack approach: 6→[6], then 4 merges with 6 to get LCM(6,4)=12→[12], then 3 merges with 12 to get LCM(12,3)=12→[12], then 2 merges with 12 to get LCM(12,2)=12→[12], finally 21 merges with 12 to get LCM(12,21)=84→[84].
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code