We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Operations to Make the Integer Zero

Difficulty: Medium


Problem Description

You are given two integers num1 and num2. In one operation, you can choose integer i in the range [0, 60] and subtract 2^i + num2 from num1. Return the integer denoting the minimum number of operations needed to make num1 equal to 0. If it is impossible to make num1 equal to 0, return -1.


Key Insights

  • Each operation allows us to subtract a value that can vary significantly based on the choice of i.
  • The operation can effectively change num1 by values influenced by num2, making the problem dependent on the relationship between num1 and num2.
  • If num2 is greater than or equal to num1, it may be impossible to reach zero, as subtracting any valid number will only yield a negative result.
  • The number of operations can be minimized by strategically choosing i to maximize the value subtracted in each step.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

To solve this problem, we can use a greedy approach where we try to maximize the value we subtract from num1 in each operation. The key steps are:

  1. Calculate the effective value we can subtract from num1 using num2 and 2^i.
  2. If num2 is greater than num1, return -1 since we cannot make num1 zero.
  3. Keep track of the number of operations needed to reach zero by iteratively subtracting the maximum possible value until num1 is less than or equal to zero.
  4. If after all possible operations num1 is not zero, return -1.

Code Solutions

def minOperations(num1: int, num2: int) -> int:
    if num2 >= num1:
        return -1
    operations = 0
    while num1 > 0:
        max_subtraction = -1
        for i in range(61):
            subtraction = (1 << i) + num2
            if subtraction > 0:
                max_subtraction = max(max_subtraction, subtraction)
        if max_subtraction == -1:
            return -1
        num1 -= max_subtraction
        operations += 1
    return operations
← Back to All Questions