Count Operations to Obtain Zero - Problem

You're given two non-negative integers num1 and num2. Your task is to perform a series of subtraction operations until one of the numbers becomes zero.

Operation Rule:

  • If num1 >= num2, subtract num2 from num1
  • Otherwise, subtract num1 from num2

Example: Starting with num1 = 5 and num2 = 4:

  1. Since 5 โ‰ฅ 4, subtract: num1 = 5 - 4 = 1, num2 = 4
  2. Since 1 < 4, subtract: num1 = 1, num2 = 4 - 1 = 3
  3. Continue until one becomes zero...

Return the total number of operations needed.

Input & Output

example_1.py โ€” Basic Case
$ Input: num1 = 2, num2 = 3
โ€บ Output: 3
๐Ÿ’ก Note: Operation 1: 2 < 3, so num2 = 3 - 2 = 1. Operation 2: 2 >= 1, so num1 = 2 - 1 = 1. Operation 3: 1 >= 1, so num1 = 1 - 1 = 0. Total: 3 operations.
example_2.py โ€” Larger Numbers
$ Input: num1 = 10, num2 = 10
โ€บ Output: 1
๐Ÿ’ก Note: Since both numbers are equal, one operation makes num1 = 10 - 10 = 0. Total: 1 operation.
example_3.py โ€” Edge Case
$ Input: num1 = 1, num2 = 1
โ€บ Output: 1
๐Ÿ’ก Note: Both numbers are 1, so after one subtraction: num1 = 1 - 1 = 0. Total: 1 operation.

Constraints

  • 0 โ‰ค num1, num2 โ‰ค 106
  • At least one of num1 or num2 will be greater than 0
  • The answer will fit in a 32-bit signed integer

Visualization

Tap to expand
Stone Pile Subtraction RacePile A: 10Pile B: 3Remove B from APile A: 1Pile B: 3Operations: 10 รท 3 = 3 (remainder 1)Then: 3 รท 1 = 3 more operationsTotal: 6 operations
Understanding the Visualization
1
Setup
Start with two piles: num1 stones and num2 stones
2
Compare
Identify which pile has more stones
3
Subtract
Remove smaller pile's count from larger pile
4
Repeat
Continue until one pile becomes empty
5
Optimize
Use division to skip multiple identical operations
Key Takeaway
๐ŸŽฏ Key Insight: This problem is essentially the Euclidean algorithm for finding GCD, but counting steps instead of finding the result!
Asked in
Amazon 15 Google 8 Microsoft 6 Apple 4
28.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen