Question 1
EasyWhat is recursion?
- A.
A function calling itself to solve smaller instances of the same problem
Popular companies
Prepare company by company
Hiring pattern, syllabus, past questions and mocks for each company.
All companiesPractice by subject
Data Structures and Algorithms
What is recursion?
A function calling itself to solve smaller instances of the same problem
Calling two functions
A loop that never ends
A data structure
Answer: A
Every recursive function needs a base case that stops the recursion.
What is a base case in recursion?
The first line of the function
A global variable
The condition under which the function returns without calling itself
The largest input
Answer: C
Without a base case the recursion never stops and the stack overflows.
What is the output of this code?
def fact(n):
return 1 if n <= 1 else n * fact(n - 1)
print(fact(5))
24
120
Answer: B
fact(5) = 5 × 4 × 3 × 2 × 1 = 120.
What is the output of this code?
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(6))
8
13
Answer: A
fib(6) with fib(0) = 0, fib(1) = 1 gives 0, 1, 1, 2, 3, 5, 8.
What happens if a recursive function has no reachable base case?
It recurses until the stack overflows
It runs once
It returns 0
The compiler fixes it
Answer: A
In Python this raises RecursionError (the default limit is about 1000 calls).
What is the output of this code?
def sum_to(n):
return 0 if n == 0 else n + sum_to(n - 1)
print(sum_to(4))
4
15
Answer: C
sum_to(4) = 4 + 3 + 2 + 1 + 0 = 10.
What is backtracking?
Building a solution step by step and undoing a step when it can't lead to a valid solution
Sorting in reverse
Reading a file from the end
Running a loop backwards
Answer: A
N-Queens, Sudoku and generating permutations are classic backtracking problems.
In a recursive function, what is the recursive case?
The function's return type
The part that stops the recursion
A loop inside the function
The part where the function calls itself on a smaller problem
Answer: D
Each recursive call should move closer to the base case.
What is the output of this code?
def f(n):
return 1 if n == 0 else n * f(n - 1)
print(f(5))
5
120
Answer: B
f computes the factorial: 5 × 4 × 3 × 2 × 1 = 120.
What is the output of this code?
def s(n):
return 0 if n == 0 else n % 10 + s(n // 10)
print(s(1234))
10
1234
Answer: A
It adds the last digit and recurses on the rest: 4 + 3 + 2 + 1 = 10.
5
720
5
21
10
6
15
24
4
24