#2169

Count Operations to Obtain Zero

Easy
MathSimulationMathematical SimulationGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log(min(num1, num2)))
Space
O(1)
O(1)
💡

Intuition

Time O(log(min(num1, num2)))Space O(1)

Instead of simulating each subtraction, we can directly calculate how many times we can subtract the smaller number from the larger one in one go. This reduces the number of operations significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a counter for operations.
  2. 2Step 2: While both numbers are greater than zero, calculate the minimum and maximum of the two numbers.
  3. 3Step 3: Use integer division to find how many times the smaller number can be subtracted from the larger number in one operation.
  4. 4Step 4: Update the larger number and increment the operations counter accordingly.
solution.py10 lines
1def countOperations(num1, num2):
2    operations = 0
3    while num1 > 0 and num2 > 0:
4        if num1 > num2:
5            operations += num1 // num2
6            num1 %= num2
7        else:
8            operations += num2 // num1
9            num2 %= num1
10    return operations

Complexity note: The complexity is O(log(min(num1, num2))) because each operation reduces the larger number significantly, leading to a logarithmic decrease.

  • 1Directly calculating how many times we can subtract in one operation saves time.
  • 2Using modulus helps in reducing the larger number efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.