Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Trace the output of a recursive function that prints before and after its recursive call.

Problem: Trace the output of a recursive function that prints before and after its recursive call.
def walk(n):
    if n == 0: return
    print(n, end=" ")
    walk(n - 1)
    print(n * 10, end=" ")
walk(3); print()
What is printed?
  1. A. 3 2 1 10 20 30
  2. B. 3 2 1 30 20 10
  3. C. 1 2 3 30 20 10
  4. D. 3 30 2 20 1 10

Correct answer: A. 3 2 1 10 20 30

Statements before the recursive call run on the way down (3, 2, 1); statements after it run as the calls return, innermost first: walk(1) prints 10, then walk(2) prints 20, then walk(3) prints 30. The call stack depth is n, so space is O(n).

More Coding Interview Problems questions

Exams that ask this topic