ProgrammingHardAmazon OA · TCS Digital
What is the extra space (memory) used by the following recursive pseudocode as a function of n, counting the call stack?
What is the extra space (memory) used by the following recursive pseudocode as a function of n, counting the call stack?
Function fib(Integer n)
if (n <= 1)
return n
end if
return fib(n - 1) + fib(n - 2)
End Function- A. O(2ⁿ)
- B. O(1)
- C. O(n)
- D. O(log n)
Correct answer: C. O(n)
Although about 2ⁿ calls are made in total, at any moment only one chain of calls is active, and the deepest chain is fib(n) → fib(n − 1) → … → fib(1), of length n. So the stack uses O(n) space; the TIME is exponential.
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? Integer pas[0..6][0..6] = all 0 for (each i from 0 to 6) pas[i][0] = 1 for (each j…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer a[8] = {4, 9, 1, 7, 3…
- What will be the output of the following pseudocode? Integer c = 0 for (each a from 1 to 20) for (each b from a to 20) for (each h from b…
- What will be the output of the following pseudocode? String s = "Tcs NQT 2024 Exam!" Integer v = 0, c = 0, d = 0, o = 0 for (each ch in s)…
- What will be the output of the following pseudocode? String s = "AAAAA", r = "" Integer i = 0 while (i < length(s)) if (i + 1 < length(s)…
- What will be the output of the following pseudocode? (code(c) gives the ASCII code: 'A' = 65, 'a' = 97, '0' = 48; ^ is XOR) Integer x =…