Space Complexity of Recursion
Solution
Add two things: the memory the calls allocate explicitly, and the call stack. Each call holds a frame on the stack until it returns, so the stack part is the maximum number of frames on the stack at any one time, which is the maximum depth of the recursion. If each frame holds a fixed number of variables, the stack part is proportional to that depth.
Solution
Time is : one call per element plus one base-case call, each doing constant work. Auxiliary space is : each call recurses before it multiplies, so the call for index 0 is still on the stack when the call for index 1 is made, and so on down to the base case. At that moment all frames are on the stack at once, so the maximum depth is .
Solution
public static int product(int[] arr) {
int result = 1;
for (int i = 0; i < arr.length; i++) {
result = result * arr[i];
}
return result;
}
Time is unchanged at . Auxiliary space changed from to : one accumulator and one index, and no stack of pending calls.
Solution
Time is : each call with makes two more calls, so the number of calls roughly doubles at each of about levels, and every call does constant work. Auxiliary space is : the deepest the stack ever gets is one chain fib(n), fib(n - 1), …, fib(1), about frames.
Time counts every call the method ever makes. Space counts only the largest number of calls that are on the stack at the same time.
Solution
public static int fib(int n) {
if (n <= 1) {
return n;
}
int prev = 0;
int curr = 1;
for (int i = 2; i <= n; i++) {
int next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
One loop from 2 to n doing constant work per pass is time. A fixed number of int variables, whatever is, is auxiliary space.
Solution
| Binary search | Best-case time | Worst-case time | Auxiliary space |
|---|---|---|---|
| Iterative | |||
| Recursive |
In the best case target is the middle element and the first comparison finds it. In the worst case target is not in the array and the range is halved about times. The time is the same for both versions. The auxiliary space is not. The loop reuses lo, hi, and mid. The recursion makes one call per halving, and those frames stay on the stack until the base case, so the stack reaches depth .