Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Operations to Make the Integer Zero solution and explanation

MediumBit ManipulationBrainteaser6 min read58.2% acceptanceUpdated 9 Apr 2026
2749. Minimum Operations to Make the Integer Zero | Leetcode Daily - PythonLeetcode Daily · 7:25 · 3K viewsWatch on YouTube
9 more videos on this problem
  1. 2749. Minimum Operations to Make the Integer Zero | Leetcode Daily - PythonLeetcode Daily · 7:25 · 3K views
  2. Minimum Operations to Make the Integer Zero | LeetCode 2749 | Bit ManipulationSanyam IIT Guwahati · 20:33 · 1K views
  3. 2749. Minimum Operations to Make the Integer Zero | Leetcode Weekly Contest 351codingMohan · 19:07 · 1K views
  4. Daily Leetcode #1984: Sep 05, 2025 - 2749. Minimum Operations to Make the Integer ZeroProgramming Live with Larry · 27:35 · 687 views
  5. LeetCode 2749 🔥 Minimum Operations to Make the Integer Zero | Daily Challenge | Bit Manipulation Study Placement · 13:42 · 560 views
  6. Leetcode 2749 Minimum Operations to Make the Integer ZeroTech Diet · 10:24 · 394 views
  7. LeetCode 2749 | Minimum Operations to Make the Integer Zero | Java Solution ExplainedcodingX krishna · 19:41 · 385 views
  8. 2749. Minimum Operations to Make the Integer Zero (Leetcode Medium)Programming Live with Larry · 29:44 · 369 views
  9. LeetCode 2749 Minimum Operations to Make the Integer Zero #leetcode #dailychallenge #python #day17Muthu Vrn · 0:39 · 191 views
  10. 2749 Minimum Operations to Make the Integer Zero LeetCodeR Sai Siddhu · 11:14 · 134 views

The problem

You are given two integers num1 and num2.

In one operation, you can choose integer i in the range [0, 60] and subtract 2i + 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.

Example 1:

Input: num1 = 3, num2 = -2
Output: 3
Explanation: We can make 3 equal to 0 with the following operations:
- We choose i = 2 and substract 22 + (-2) from 3, 3 - (4 + (-2)) = 1.
- We choose i = 2 and substract 22 + (-2) from 1, 1 - (4 + (-2)) = -1.
- We choose i = 0 and substract 20 + (-2) from -1, (-1) - (1 + (-2)) = 0.
It can be proven, that 3 is the minimum number of operations that we need to perform.

Example 2:

Input: num1 = 5, num2 = 7
Output: -1
Explanation: It can be proven, that it is impossible to make 5 equal to 0 with the given operation.

Constraints:

  • 1 <= num1 <= 109
  • -109 <= num2 <= 109

Approach overview

Problem Overview: You start with two integers num1 and num2. In one operation you subtract (2^i + num2) from num1 for any non‑negative i. The goal is to reach exactly zero using the minimum number of operations.

Approach 1: Greedy Subtraction with Powers of 2 (O(60) time, O(1) space)

The key observation is that after performing k operations, the total value removed from the powers of two is x = num1 - k * num2. That means you must express x as the sum of exactly k powers of two. Using bit manipulation, this becomes a constraint on the binary representation of x. The number of set bits (popcount(x)) must be ≤ k because each set bit already represents one power of two, and larger powers can be split into smaller ones if more operations are needed.

You iterate over possible operation counts k (typically up to 60 because 2^60 exceeds the input bounds). For each k, compute x = num1 - k * num2. A valid solution exists if x ≥ k and popcount(x) ≤ k. The first k satisfying these conditions is the minimum number of operations. This greedy check works because any integer can be decomposed into powers of two using its binary form. The approach is extremely fast and relies heavily on properties of binary representation.

Approach 2: Dynamic Programming (DP) for Minimization (O(K * B) time, O(K) space)

A more explicit strategy models the process with dynamic programming. Treat each operation as selecting a power 2^i and subtracting num2 along with it. The DP tracks the minimum operations required to form different sums of powers of two while accounting for the cumulative subtraction of num2. Each state represents how many operations have been used and the achievable remainder value.

You iterate over possible powers of two and update states similarly to a knapsack transition. While this approach demonstrates the structure of the problem, the state space grows quickly because powers can repeat and the target value changes with every operation. In practice, DP is slower and more complex than the greedy insight derived from binary decomposition.

Recommended for interviews: The greedy check using popcount and binary constraints is the expected solution. It shows strong understanding of bit manipulation and mathematical reasoning. Mentioning a DP formulation can demonstrate problem exploration, but the constant‑time greedy iteration is what interviewers usually look for.

Approach 1: Approach 1: Greedy Subtraction with Powers of 2

This approach involves using a greedy method to subtract the largest possible power of 2 plus num2 from num1. At each step, we try to maximize the decrease in num1, aiming to reach exactly zero. If it becomes impossible to subtract without going below zero or exceeding the potential operations limit, we return -1.

def min_operations(num1, num2):
    count = 0
    while num1 > 0:
        found = False
        for i in range(60, -1, -1):
            if (num1 - (2**i + num2)) >= 0:
                num1 -= (2**i + num2)
                count += 1
                found = True
                break
        if not found:
            return -1
    return count
public int minOperations(int num1, int num2) {
    int count = 0;
    while (num1 > 0) {
        boolean found = false;
        for (int i = 60; i >= 0; i--) {
            int subtractor = (1 << i) + num2;
            if (num1 - subtractor >= 0) {
                num1 -= subtractor;
                count++;
                found = true;
                break;
            }
        }
        if (!found) return -1;
    }
    return count;
}

The function iteratively subtracts the largest valid (2^i + num2) from num1. It counts the operations until num1 becomes zero. If num1 becomes negative and no valid i can be found, it returns -1.

Complexity

Time Complexity: O(1) due to loop limits.
Space Complexity: O(1), only a few variables are used.

Try this approach in the editor

Approach 2: Approach 2: Dynamic Programming (DP) for Minimization

This approach leverages dynamic programming to store intermediate results of subproblems, reducing redundant calculations. We systematically explore the impact of subtracting each (2^i + num2) on num1, storing the minimum steps required to reach zero. This method is effective but requires more memory management.

#include <vector>
#include <limits.h>

int minOperations(int num1, int num2) {
    std::vector<int> dp(num1 + 1, INT_MAX);
    dp[0] = 0;
    for (int i = 1; i <= num1; ++i) {
        for (int j = 0; j <= 60; ++j) {
            int val = (1 << j) + num2;
            if (i >= val && dp[i - val] != INT_MAX) {
                dp[i] = std::min(dp[i], dp[i - val] + 1);
            }
        }
    }
    return dp[num1] == INT_MAX ? -1 : dp[num1];
}
function minOperations(num1, num2) {
    const dp = new Array(num1 + 1).fill(Infinity);
    dp[0] = 0;
    for (let i = 1; i <= num1; i++) {
        for (let j = 0; j <= 60; j++) {
            const val = (1 << j) + num2;
            if (i >= val && dp[i - val] !== Infinity) {
                dp[i] = Math.min(dp[i], dp[i - val] + 1);
            }
        }
    }
    return dp[num1] === Infinity ? -1 : dp[num1];
}

This DP solution initializes a DP array where each index represents the minimum operations needed for that particular num1 value. Each valid operation updates the DP based on historical values.

Complexity

Time Complexity: O(num1 * 61), for each num1 value, checks up to 61 possibilities for i.
Space Complexity: O(num1), required to store DP results for each subproblem.

Try this approach in the editor

Approach 3: Enumeration

If we operate k times, then the problem essentially becomes: determining whether num1 - k times num2 can be split into the sum of k 2^is.

Let's assume x = num1 - k times num2. Next, we discuss in categories:

  • If x < 0, then x cannot be split into the sum of k 2^is, because 2^i > 0, which obviously has no solution;
  • If the number of 1s in the binary representation of x is greater than k, there is also no solution in this case;
  • Otherwise, for the current k, there must exist a splitting scheme.

Therefore, we start enumerating k from 1. Once we find a k that meets the condition, we can directly return the answer.

The time complexity is O(log x), and the space complexity is O(1).

function makeTheIntegerZero(num1: number, num2: number): number {
    for (let k = 1; ; ++k) {
        let x = num1 - k * num2;
        if (x < 0) {
            break;
        }
        if (x.toString(2).replace(/0/g, '').length <= k && k <= x) {
            return k;
        }
    }
    return -1;
}
public class Solution {
    public int MakeTheIntegerZero(int num1, int num2) {
        long a = num1, b = num2;
        for (long k = 1; ; ++k) {
            long x = a - k * b;
            if (x < 0) {
                break;
            }
            if (BitOperations.PopCount((ulong)x) <= k && k <= x) {
                return (int)k;
            }
        }
        return -1;
    }
}
func makeTheIntegerZero(num1 int, num2 int) int {
	for k := 1; ; k++ {
		x := num1 - k*num2
		if x < 0 {
			break
		}
		if bits.OnesCount(uint(x)) <= k && k <= x {
			return k
		}
	}
	return -1
}
impl Solution {
    pub fn make_the_integer_zero(num1: i32, num2: i32) -> i32 {
        let num1 = num1 as i64;
        let num2 = num2 as i64;
        for k in 1.. {
            let x = num1 - k * num2;
            if x < 0 {
                break;
            }
            if (x.count_ones() as i64) <= k && k <= x {
                return k as i32;
            }
        }
        -1
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Greedy Subtraction with Powers of 2

Time Complexity: O(1) due to loop limits.
Space Complexity: O(1), only a few variables are used.

Approach 2: Dynamic Programming (DP) for Minimization

Time Complexity: O(num1 * 61), for each num1 value, checks up to 61 possibilities for i.
Space Complexity: O(num1), required to store DP results for each subproblem.

Enumeration–

Complexity analysis

ApproachTimeSpaceWhen to Use
Greedy Subtraction with Powers of 2O(60)O(1)Best general solution using bit manipulation and binary popcount checks
Dynamic Programming for MinimizationO(K * B)O(K)Useful for conceptual understanding or when modeling the process explicitly

Frequently asked questions

Is Minimum Operations to Make the Integer Zero easy or hard?

The problem is rated Medium on LeetCode. The implementation is short, but the key insight—transforming the operations into constraints on the binary representation of num1 - k * num2—makes it a brainteaser that requires bit manipulation reasoning.

Minimum Operations to Make the Integer Zero Python/Java solution

Python and Java implementations both follow the same idea: iterate k from 1 to around 60, compute x = num1 - k * num2, and verify the constraints x ≥ k and bitCount(x) ≤ k. Python typically uses bin(x).count('1') while Java uses Integer.bitCount or Long.bitCount.

How to solve Minimum Operations to Make the Integer Zero in O(n)?

The problem can actually be solved faster than O(n). Iterate over possible operation counts k and compute x = num1 - k * num2. If x is non‑negative, popcount(x) ≤ k, and x ≥ k, then k operations can construct the value using powers of two. The first valid k is the answer.

What is the best approach for Minimum Operations to Make the Integer Zero?

The optimal approach iterates over the number of operations k and checks whether num1 - k * num2 can be represented as a sum of k powers of two. Using bit manipulation, the condition becomes popcount(x) ≤ k and x ≥ k where x = num1 - k * num2. This greedy check runs in constant time because k only needs to be tested up to about 60.

Is Minimum Operations to Make the Integer Zero asked at Google/Amazon/Meta?

Problems involving binary decomposition and bit manipulation frequently appear in interviews at companies like Google, Amazon, and Meta. This question tests reasoning about binary representation and greedy constraints, which are common themes in system‑level algorithm interviews.

What data structure is used in Minimum Operations to Make the Integer Zero?

The main technique is bit manipulation rather than a complex data structure. The algorithm relies on checking the number of set bits (popcount) in the binary representation of an integer and performing simple arithmetic operations.

What is the time complexity of Minimum Operations to Make the Integer Zero?

The optimal greedy solution runs in O(60) time and O(1) space. The algorithm only checks at most 60 possible operation counts because larger values exceed the limits of 64‑bit integers. Each iteration performs constant‑time arithmetic and a popcount operation.

Comments

Now write it yourselfClose this page and solve Minimum Operations to Make the Integer Zero in the editor, without looking.
Practise Minimum Operations to Make the Integer Zero