Problem
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 thefinal 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
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^5
- The test cases are generated such that the values in the final array are less than or equal to
108
.
Solution
Method 1 - Stack Simulation with GCD/LCM
Intuition
We want to repeatedly merge adjacent non-coprime numbers into their LCM until no such pairs remain. Using a stack, we can efficiently simulate this process: for each number, merge it with the top of the stack as long as the GCD is greater than 1.
Approach
- Initialize an empty stack.
- For each number in nums:
- While the stack is not empty and the top and current number are non-coprime (GCD > 1), pop the top and replace current with LCM(top, current).
- Push the current number onto the stack.
- The stack contains the final array.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity: O(N log M), where N is the length of nums and M is the max value in nums (for GCD/LCM).
- 🧺 Space complexity: O(N), for the stack.