Minimum Number of Operations to Make All Array Elements Equal to 1 - Problem
You are given a 0-indexed array nums consisting of positive integers. You can do the following operation on the array any number of times:
- Select an index
isuch that0 <= i < n - 1and replace either ofnums[i]ornums[i+1]with their gcd value.
Return the minimum number of operations to make all elements of nums equal to 1. If it is impossible, return -1.
The gcd of two integers is the greatest common divisor of the two integers.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,6,3,4]
›
Output:
4
💡 Note:
Find shortest subarray with GCD=1. [2,6,3] has GCD=1 with length 3. Operations: (3-1) to reduce subarray + (4-1) to spread = 2+3 = 5. But optimal is different - need 4 operations total.
Example 2 — Already Has 1
$
Input:
nums = [2,10,6,14]
›
Output:
-1
💡 Note:
GCD of entire array is 2 > 1, and no subarray can produce GCD=1, so impossible.
Example 3 — Contains 1
$
Input:
nums = [2,1,3]
›
Output:
2
💡 Note:
Array already contains 1 at index 1. Need 2 operations to make other elements equal to 1.
Constraints
- 1 ≤ nums.length ≤ 50
- 1 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array [2,6,3,4] where we need all elements to become 1
2
Find GCD Subarray
Identify shortest subarray with GCD=1 for optimal path
3
Calculate Operations
Reduce subarray + spread 1s = minimum operations needed
Key Takeaway
🎯 Key Insight: Find the shortest subarray with GCD=1, then calculate total operations needed to transform the entire array
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code