def foo(n):
def bar(n):
if n == 0:
return 0
else:
return 1 + bar (n - 1)
return n * bar(n)
How can I calculate what is the time complexity for the running time of foo in terms of its input n? What about space complexity?
Let's break it down:
return n * bar(n)
→ n * (1 + bar(n - 1))
→ n * (1 + 1 + bar(n - 2))
→ n * (1 + 1 + 1 + bar(n - 3))
→ n * (1 + 1 + 1 + .... <n times> + bar(0))
→ n * n
This appears linear in time and memory - O(n)
.