Problem Description
Given an array of positive integers, you are allowed to perform operations where you choose an index i (0 <= i < n-1) and replace either nums[i] or nums[i+1] with the greatest common divisor (gcd) of nums[i] and nums[i+1]. The goal is to make every element in the array equal to 1 using the minimum number of operations. If it is impossible to achieve this, return -1.
Key Insights
- If at least one element is already 1, then that element can be used to convert its neighbors to 1. Hence, the number of operations in this case is simply (n - number of ones).
- If no element is 1, then check if the overall gcd of the array is 1; if it isn’t, it is impossible to make every element 1.
- Otherwise, find the smallest subarray for which the cumulative gcd becomes 1. Converting that subarray into a 1 uses (L - 1) operations (where L is the length of the subarray). Then use the newly created 1 to turn the rest of the elements into 1 with an additional (n - 1) operations.
- The final answer will be the sum of these two parts.
Space and Time Complexity
Time Complexity: O(n^2) in the worst-case, where n is the length of the array
Space Complexity: O(1) extra space (ignoring the input list)
Solution
The solution works in two main parts:
-
First, scan through the array to count how many elements are 1. If at least one exists, then the answer is (n - count1) because each non-1 element can be paired with a nearby 1 in one operation.
-
If there are no ones, compute the overall gcd of the array. If the overall gcd is not 1, return -1. Otherwise, iterate through every possible subarray, and for each subarray compute its cumulative gcd. If the gcd becomes 1 for a subarray starting at index i and ending at j, track the shortest length (j - i). The operations needed will be (length of subarray - 1) for creating the first 1, plus (n - 1) to spread that 1 to all remaining elements.
The algorithm relies heavily on gcd computations and a brute force two-loop approach over the small maximum input size (n ≤ 50).