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

ArrayMathNumber Theory

Explanation

To solve this problem, we can iterate through the array and try to make all elements equal to 1. We will keep track of the operations needed to achieve this. We will use the property that the GCD of a number and 1 is always 1. We will start by finding the GCD of adjacent elements and replacing one of them with the GCD value until all elements are equal to 1. If at any point we encounter a number that is not divisible by 1, we know it is impossible to make all elements equal to 1.

Algorithm:

  1. Iterate through the array and find the GCD of each pair of adjacent elements.
  2. Replace one of the elements with the GCD value and increment the operations count.
  3. Continue this process until all elements are equal to 1 or it is impossible.
  4. Return the minimum number of operations required to make all elements equal to 1.

Time Complexity: O(nlog(max(nums))) Space Complexity: O(1)

class Solution {
    public int minOperations(int[] nums) {
        int n = nums.length;
        int operations = 0;
        
        for (int i = 0; i < n - 1; i++) {
            if (nums[i] % 2 != 0) {
                return -1; // If any number is not divisible by 2, it is impossible
            }
            
            int gcd = gcd(nums[i], nums[i + 1]);
            nums[i + 1] = gcd;
            operations++;
        }
        
        return operations;
    }
    
    private int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.