LeetCode Entry
2169. Count Operations to Obtain Zero
Count numbers subtractions until 0
2169. Count Operations to Obtain Zero easy blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1168
Problem TLDR
Count numbers subtractions until 0 #easy
Intuition
Simulate the process.
Another way to look at it: the biggest would be subtracted big/small times until numbers flip.
Approach
- recursion space complexity is log(depth)
- it is Euclidian algorithm (a,b) to (b, a%b)
- there is a golden ratio hidden here
- consequtive Fibonacci numbers would give the slowest path: Fibonacci sequence backwards
Complexity
-
Time complexity: \(O(log(n))\)
-
Space complexity: \(O(log(n))\)
Code
// 0ms
fun countOperations(a: Int, b: Int): Int =
if (a<1||b<1) 0 else a/b + countOperations(b,a%b)
// 0ms
pub fn count_operations(a: i32, b: i32) -> i32 {
if a<1 || b<1 { 0 } else { a/b + Self::count_operations(b,a%b) }
}