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 i such that 0 <= i < n - 1 and replace either of nums[i] or nums[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
Minimum Operations to Make All Elements Equal to 1 INPUT nums array: 2 i=0 6 i=1 3 i=2 4 i=3 GCD Values: gcd(2,6) = 2 gcd(6,3) = 3 gcd(3,4) = 1 Find subarray with GCD=1: gcd(3,4) = 1 at [i=2,i=3] Shortest length: 2 Count of 1s in array: 0 Array length n = 4 ALGORITHM STEPS 1 Check for existing 1s If 1 exists, count = n - ones 2 Find min subarray GCD=1 Check all subarrays for GCD=1 3 Calculate operations ops = (minLen-1) + (n-1) 4 Return result Return -1 if no GCD=1 found Calculation for nums=[2,6,3,4]: minLen = 2 (subarray [3,4]) n = 4 ops to get first 1: minLen - 1 = 2 - 1 = 1 ops to convert rest: n - 1 = 4 - 1 = 3 FINAL RESULT Total Operations: 4 Formula: (minLen-1) + (n-1) = (2-1) + (4-1) = 1 + 3 = 4 Transformation Steps: Start: [2,6,3,4] Op 1: gcd(3,4)=1 --> [2,6,1,4] Op 2: gcd(6,1)=1 --> [2,1,1,4] Op 3: gcd(2,1)=1 --> [1,1,1,4] Op 4: gcd(1,4)=1 --> [1,1,1,1] OK Key Insight: If no 1 exists in array, find the shortest subarray with GCD equal to 1. This requires (length-1) operations to create first 1. Then spread that 1 to remaining (n-1) elements in (n-1) more operations. If overall GCD of array is not 1, it's impossible to make all elements 1, so return -1. Time Complexity: O(n^2 * log(max)) | Space Complexity: O(1) TutorialsPoint - Minimum Number of Operations to Make All Array Elements Equal to 1 | Subarray GCD Analysis
Asked in
Google 12 Microsoft 8
8.5K Views
Medium Frequency
~25 min Avg. Time
156 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen