Skip to main content

Minimum Number of Operations to Make All Array Elements Equal to 1 - Solution & Explanation

MediumArrayMathNumber Theory22 min readAsked at: Amazon, Google
Practice this problem

Problem Statement

You are given a 0-indexed array nums consisiting 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.

 

Example 1:

Input: nums = [2,6,3,4]
Output: 4
Explanation: We can do the following operations:
- Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4].
- Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4].
- Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4].
- Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1].

Example 2:

Input: nums = [2,10,6,14]
Output: -1
Explanation: It can be shown that it is impossible to make all the elements equal to 1.

 

Constraints:

  • 2 <= nums.length <= 50
  • 1 <= nums[i] <= 106

Approach Overview

Problem Overview: You are given an integer array where one operation replaces nums[i] with gcd(nums[i], nums[i+1]). The goal is to determine the minimum number of operations required to make every element equal to 1. If it’s impossible, return -1. The key observation is that once a single 1 exists in the array, you can propagate it across the array using adjacent GCD operations.

Approach 1: Brute Force by Iterating Over All Pairs (O(n² log A) time, O(1) space)

Start by checking how many elements are already equal to 1. If at least one exists, the remaining elements can be converted using adjacent operations in n - countOfOnes steps. If there are no 1s, search for the smallest subarray whose GCD becomes 1. Use two nested loops: fix a start index, expand the end index, and update the running GCD using gcd(currentGcd, nums[j]). The first time the GCD becomes 1, you know how many operations are required to create a 1 in that segment. Track the minimum length across all pairs.

This approach relies heavily on properties of the number theory concept of GCD. Each GCD computation takes O(log A), giving an overall complexity of O(n² log A). The algorithm uses only a few variables, so space complexity remains constant.

Approach 2: Optimized Scan from Left (O(n² log A) time, O(1) space)

This version improves the brute force idea by scanning the array from left to right and stopping early whenever the running GCD becomes 1. For each starting index i, compute the cumulative GCD while expanding the right pointer. As soon as the GCD becomes 1, the segment can generate a single 1 in length - 1 operations. Once that 1 exists, converting the rest of the array takes another n - 1 operations.

The algorithm keeps track of the shortest segment that produces GCD 1. If none exists, it means the overall array GCD is greater than 1, so producing a 1 is impossible. This optimized scan avoids unnecessary expansions once a valid segment is found and works well for typical constraints.

The logic combines array traversal with repeated GCD reduction from math. The main insight: create a single 1 as cheaply as possible, then spread it across the array.

Recommended for interviews: The optimized left‑scan approach. Interviewers expect you to recognize the GCD property and minimize the subarray length that yields 1. Starting with brute force shows you understand the mechanics, but identifying the shortest GCD‑1 segment demonstrates stronger algorithmic reasoning.

Approach 1: Brute Force by Iterating Over All Pairs

This approach involves iterating over every possible subarray and calculating the GCD of the subarray. The idea is to find the shortest subarray that has a GCD of 1, indicating that the elements in this subarray can eventually be reduced to ones using successive GCD operations.

This C solution iterates over every subarray of nums. For each subarray, it computes the GCD and checks if it becomes 1. Once the GCD is 1, it determines the number of operations taken to reach that state. It keeps track of the shortest subarray that can become 1, thereby minimizing operations.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

The time complexity of this solution is O(n^2) since it involves checking every subarray in the array. The space complexity is O(1) as it uses a fixed amount of space for the GCD calculation.

Try this approach in the editor →

Approach 2: Optimized Scan from Left

In this method, we take advantage of the properties of the GCD to search efficiently. We design an algorithm that tries to resolve the problem by linearly scanning for opportunities to achieve a GCD of 1, minimizing redundant calculations.

This C code first checks if the overall GCD of the array is greater than 1, which immediately means conversion to all 1s isn't possible. Next, it looks for the shortest subarray with a GCD of 1, counting needed operations.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

The time complexity is O(n^2) due to nested loops, but optimizations reduce redundant calculations after overall GCD check. The space complexity remains O(1), with only a few temporary variables.

Try this approach in the editor →

Approach 3: Math

We first count the number of 1s in the array nums as cnt. If cnt \gt 0, then we only need n - cnt operations to turn the entire array into 1s.

Otherwise, we need to first turn one element in the array into 1, and then the minimum number of remaining operations is n - 1.

Consider how to turn one element in the array into 1 while minimizing the number of operations. In fact, we only need to find a minimum contiguous subarray interval nums[i,..j] such that the greatest common divisor of all elements in the subarray is 1, with the subarray length being mi = min(mi, j - i + 1). Finally, our total number of operations is n - 1 + mi - 1.

The time complexity is O(n times (n + log M)) and the space complexity is O(log M), where n and M are the length of the array nums and the maximum value in the array nums, respectively.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Brute Force by Iterating Over All Pairs

The time complexity of this solution is O(n^2) since it involves checking every subarray in the array. The space complexity is O(1) as it uses a fixed amount of space for the GCD calculation.

Optimized Scan from Left

The time complexity is O(n^2) due to nested loops, but optimizations reduce redundant calculations after overall GCD check. The space complexity remains O(1), with only a few temporary variables.

Math

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force by Iterating Over All PairsO(n² log A)O(1)When first exploring the problem and validating how GCD propagation works across subarrays.
Optimized Scan from LeftO(n² log A)O(1)General case. Finds the shortest subarray with GCD = 1 and minimizes operations.

Video Solution

Minimum Number of Operations to Make All Array Elements Equal to 1 | Easy Intuition | Leetcode 2654codestorywithMIK8,260 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Minimum Number of Operations to Make All Array Elements Equal to 1 easy or hard?
The problem is rated Medium because it requires recognizing a number theory insight rather than just simulating operations. The difficulty lies in realizing that generating a single 1 through GCD operations enables converting the entire array efficiently.
Minimum Number of Operations to Make All Array Elements Equal to 1 Python/Java solution
Most implementations follow the same structure: count existing ones first, then scan all subarrays while maintaining a running GCD. Python uses math.gcd, while Java typically uses a custom gcd method. Both implementations run in O(n² log A) time with O(1) extra space.
How to solve Minimum Number of Operations to Make All Array Elements Equal to 1 in O(n)?
A strict O(n) solution generally isn't possible because multiple GCD computations across subarrays are required. The practical optimized solution scans subarrays and updates the running GCD, resulting in O(n² log A) complexity while using constant extra space.
What is the best approach for Minimum Number of Operations to Make All Array Elements Equal to 1?
The best approach scans the array to find the shortest subarray whose GCD becomes 1. Once a single 1 is produced, it can be propagated across the entire array using adjacent operations. This method runs in O(n² log A) time due to repeated GCD calculations and uses O(1) extra space.
Is Minimum Number of Operations to Make All Array Elements Equal to 1 asked at Google/Amazon/Meta?
Problems combining GCD operations with array transformations frequently appear in interviews at companies like Google, Amazon, and Meta. Variants that require recognizing number theory properties and minimizing operations are common in medium‑difficulty interview rounds.
What data structure is used in Minimum Number of Operations to Make All Array Elements Equal to 1?
The problem primarily uses arrays with mathematical GCD operations. No advanced data structures are required. The key concept comes from number theory, specifically repeated GCD reduction across contiguous array segments.
What is the time complexity of Minimum Number of Operations to Make All Array Elements Equal to 1?
The typical optimal solution runs in O(n² log A) time, where n is the array length and A is the maximum element value. The log A factor comes from the Euclidean algorithm used to compute GCD repeatedly while expanding subarrays.

Ready to solve this problem?

Practice Minimum Number of Operations to Make All Array Elements Equal to 1 with our built-in code editor and test cases.

Practice on FleetCode