Problem Description
Given an array of integers, repeatedly find any two adjacent numbers that are non-coprime (i.e. their greatest common divisor is greater than 1) and replace them with their least common multiple (LCM). Continue this process until no such adjacent pair exists. The result is guaranteed to be unique regardless of the order of operations.
Key Insights
- Use a stack to simulate merging adjacent non-coprime numbers.
- Check the top of the stack with the current number and merge as long as they are non-coprime.
- Merging is done by computing the LCM and then rechecking with the new top of the stack.
- Euclid’s algorithm is used to compute the greatest common divisor (GCD).
- The result is independent of the order of merging, which simplifies the solution.
Space and Time Complexity
Time Complexity: O(n * log(max(nums))) on average, since each merge operation involves computing GCD which takes logarithmic time. Space Complexity: O(n) for the stack storage.
Solution
The solution uses a stack-based approach. We iterate over the input array and for each number, we:
- Check the top of the stack to see if it is non-coprime with the current number.
- If they are non-coprime (GCD > 1), compute the LCM of these two numbers, pop the stack, and use the LCM as the new candidate.
- Continue merging with the new candidate until no adjacent non-coprime pair is found.
- Push the final candidate on the stack. This algorithm effectively simulates the replacement process, ensuring that only adjacent pairs are merged and handling cascaded merges correctly.