Leetcode #2654: Minimum Number of Operations to Make All Array Elements Equal to 1
In this guide, we solve Leetcode #2654 Minimum Number of Operations to Make All Array Elements Equal to 1 in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Math, Number Theory
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
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].
Python Solution
class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
cnt = nums.count(1)
if cnt:
return n - cnt
mi = n + 1
for i in range(n):
g = 0
for j in range(i, n):
g = gcd(g, nums[j])
if g == 1:
mi = min(mi, j - i + 1)
return -1 if mi > n else n - 1 + mi - 1
Complexity
The time complexity is and the space complexity is , where and are the length of the array and the maximum value in the array , respectively. The space complexity is , where and are the length of the array and the maximum value in the array , respectively.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.