Minimum Number of Operations to Make All Array Elements Equal to 1 — LeetCode 2654 Python Solution

MediumArrayMathNumber Theory
Problem
#2654
Reading time
3 min

The 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.

Example

Input
nums = [2,6,3,4]
Output
4
Explanation
We can do the following operations:

Python solution

Python
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

MeasureComplexity
TimeO(n \times (n + \log M))
SpaceO(\log M), where n and M are the length of the array nums and the maximum value in the array nums, respectively auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2654. Minimum Number of Operations to Make All Array Elements Equal to 1?
LeetCode 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 is rated Medium on LeetCode.
What is the time complexity of LeetCode 2654. Minimum Number of Operations to Make All Array Elements Equal to 1?
The Python solution on this page runs in O(n \times (n + \log M)).
What is the space complexity of LeetCode 2654. Minimum Number of Operations to Make All Array Elements Equal to 1?
The Python solution on this page uses O(\log M), where n and M are the length of the array nums and the maximum value in the array nums, respectively auxiliary space.
What topics does LeetCode 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 cover?
LeetCode 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 is tagged Array, Math and Number Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview