Leetcode 2654: Minimum Number of Operations to Make All Array Elements Equal to 1

grid47
grid47
Exploring patterns and algorithms
Feb 15, 2024 7 min read

You are given an array of positive integers ’nums’. You can perform an operation on this array where you select two consecutive elements and replace one of them with the gcd (greatest common divisor) of the two elements. The goal is to make all elements of the array equal to 1 using the minimum number of operations. If it’s impossible to make all elements equal to 1, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of positive integers, nums, with a length between 2 and 50. The integers in nums can be as large as 10^6.
Example: Input: nums = [3, 9, 6, 12]
Constraints:
• 2 <= nums.length <= 50
• 1 <= nums[i] <= 10^6
Output: Return the minimum number of operations required to make all elements in the array equal to 1, or return -1 if it is impossible.
Example: Output: 3
Constraints:
• The output should be an integer representing the minimum number of operations or -1 if it's impossible.
Goal: The goal is to find the minimum number of operations to convert all elements of the array to 1 by using gcd operations on consecutive elements.
Steps:
• Step 1: Check if the array already contains 1. If so, return the number of operations required to change all elements to 1.
• Step 2: For each subarray of consecutive elements, calculate their gcd and check if it's 1.
• Step 3: Track the minimum number of steps needed to achieve an array of all ones by applying gcd operations iteratively on the elements.
Goal: The solution must efficiently handle arrays of size up to 50 and integer values up to 10^6.
Steps:
• The solution should work for n = 50 and handle large values of nums[i] efficiently.
Assumptions:
• The array nums will always have at least two elements.
• If it's possible to convert the entire array to 1, it can be done using a series of gcd operations on consecutive elements.
Input: Input: nums = [3, 9, 6, 12]
Explanation: In this case, we can perform the following operations: 3 and 9 have gcd 3, then 9 and 6 have gcd 3, and finally 6 and 12 have gcd 6. Using gcd on consecutive elements, we eventually convert all elements to 1 after 3 operations.

Input: Input: nums = [5, 15, 25]
Explanation: For this case, we cannot reduce these elements to 1 since their gcd is greater than 1. Therefore, it is impossible to make all elements equal to 1, and the output is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus