LeetCode has an Integer Replacement problem defined as follows:
Given a positive integer $n$, you can apply one of the following operations:
- If $n$ is even, replace $n$ with $n / 2$.
- If $n$ is odd, replace $n$ with either $n + 1$ or $n - 1$.
Return the minimum number of operations needed for $n$ to become $1$.
I would like to determine the time and space complexity of a naive tree-recursive algorithm that uses memoization (caching to avoid recalculation). Here is the Python implementation:
class Solution:
def __init__(self):
self.results = {1: 0} # specifies 1 as the base case requiring 0 operations
def integerReplacement(self, n: int) -> int:
if n not in self.results:
if n % 2: # n odd
self.results[n] = 1 + min(
self.integerReplacement(n + 1),
self.integerReplacement(n - 1)
)
else: # n even
self.results[n] = 1 + self.integerReplacement(n / 2)
return self.results[n]
If this were tree recursive in all cases, the running time would be $O(2^n)$ because the branching factor is two; however, this is tree recursive only half the time. What is the time complexity of this algorithm? I am also interested in the space complexity, which I know would depend on the greater of the maximum stack depth and hash table size.