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?- A. 3 2 1 10 20 30
- B. 3 2 1 30 20 10
- C. 1 2 3 30 20 10
- 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
- Problem: Sum the values of all LEFT leaves (leaves that are the left child of their parent). Trees are built from a level-order list by…
- Problem: Return (level, sum) of the level with the largest sum, levels numbered from 1 (smallest level on ties). Trees are built from a…
- Problem: Each root-to-leaf path spells a number (digits from root to leaf). Return the sum of these numbers. Trees are built from a…
- Problem: Split a string into pieces that are all palindromes and list every such partition (backtracking). python def palparts(s): res =…
- Problem: Find all combinations of unlimited-use stamp values that total exactly 15 (each combination listed once, in non-decreasing…
- Problem: Restore all valid IPv4 addresses from a digit string (four parts, each 0–255, no leading zeros except "0"). python def…