ProgrammingHardAccenture · Cognizant pattern
What is the space complexity (auxiliary stack space) of the following recursive factorial function for input n?
What is the space complexity (auxiliary stack space) of the following recursive factorial function for input n?
Function fact(Integer n)
if (n <= 1)
return 1
end if
return n * fact(n - 1)
End Function- A. O(1)
- B. O(log n)
- C. O(n)
- D. O(n^2)
Correct answer: C. O(n)
Each recursive call adds one more frame to the call stack before any of them return (since the multiplication happens after the recursive call completes), so the maximum stack depth grows linearly with n, giving O(n) auxiliary space.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode (anagram check via sorting)? Function isAnagram(String a, String b) return…
- What will be the output of the following pseudocode (duplicate detection using a set)? Function hasDuplicate(Array arr) Set seen = empty…
- What will be the output of the following pseudocode (maximum sum of any window of size k)? (Arrays are indexed from 0.) Integer arr[6] =…
- What will be the output of the following pseudocode (counting inversions, brute force)? (Arrays are indexed from 0.) Integer arr[5] = {2…
- What will be the output of the following pseudocode (counting pairs summing to a target, brute force)? (Arrays are indexed from 0.)…
- What will be the output of the following pseudocode (counting pattern occurrences, allowing overlaps)? Function countOcc(String text…