Data Structures & AlgorithmsVery hardGATE CS · TCS NQT · Product Company SDE
What is the space complexity of this recursive factorial function, as a function of n (ignoring the final integer result size)?
What is the space complexity of this recursive factorial function, as a function of n (ignoring the final integer result size)?
int fact(int n) {
if (n == 0) return 1;
return n * fact(n - 1);
}- A. O(1)
- B. O(n)
- C. O(log n)
- D. O(n^2)
Correct answer: B. O(n)
Each call stays on the call stack until its recursive call returns, so the stack depth grows to n before unwinding: O(n) space, not O(1).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Evaluate the postfix expression: 6 3 + 7 + 9 +
- Evaluate the postfix expression: 1 1 - 5 - 5 -
- Heap sort (build a max-heap, then repeatedly swap the root with the last unsorted element and sift down) is run on [91, 96, 8, 20, 80, 10…
- Using a monotonic (decreasing) stack to find, for each element of [32, 3, 22, 30, 36, 26, 11, 9], the next element to its right that is…
- Quicksort uses the Lomuto partition with the last element as pivot on [42, 63, 77, 95, 70, 32, 1, 32, 76]. After one partition call, at…
- Evaluate the postfix expression: 5 9 + 4 2 +