Count Operations to Obtain Zero — LeetCode 2169 Python Solution

EasyMathSimulation
Problem
#2169
Reading time
2 min

The problem

You are given two non-negative integers num1 and num2. In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2.

Example

Input
num1 = 2, num2 = 3
Output
3
Explanation
- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.

Python solution

Python
class Solution:
    def countOperations(self, num1: int, num2: int) -> int:
        ans = 0
        while num1 and num2:
            if num1 >= num2:
                num1 -= num2
            else:
                num2 -= num1
            ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(m), where m is the maximum of \textit{num1} and \textit{num2}
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2169. Count Operations to Obtain Zero is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2169. Count Operations to Obtain Zero?
LeetCode 2169. Count Operations to Obtain Zero is rated Easy on LeetCode.
What is the time complexity of LeetCode 2169. Count Operations to Obtain Zero?
The Python solution on this page runs in O(m), where m is the maximum of \textit{num1} and \textit{num2}.
What is the space complexity of LeetCode 2169. Count Operations to Obtain Zero?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2169. Count Operations to Obtain Zero cover?
LeetCode 2169. Count Operations to Obtain Zero is tagged Math and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview