Recursion Flashcards

(6 cards)

1
Q

What are indicators that a problem needs to be solved with recursion?

A
  • When I can break it into subproblems
  • When there is some sort of repetition
  • When a recursive data structure is involved
  • Trees and BST (almost always you should think about recursion)
  • Array or List: A[0..N] = A[0] + A[1..n] or A[0..mid] + A[mid+1..N]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do I solve a recursion problem?

A

You need to answer these questions clearly:

A. Find the recursive relationship

B. What are the subproblems?

C. How do we combine them?

D. What is the base case?

E. Try to draw the recursion tree.
Root: is the overall problem
Children of the root: subproblems
Leaves: Base cases

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are some famous recursion problems?

A

Famous:
- nth Fibonacci
- POW (power) problem
- Factorial problem
- Any tree traversal
- Binary search
- merge sort
- coin change

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the key insight about recursion?

A

Every recursive function is really DFS on the recursion tree
Recursion -> DFS -> Recursion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the template for a recursion problem?

A

def dfs(state):
# IMPLEMENT base case

if …is_basecase(state):
return …

IMPLEMENT recursive formula
ans = …combine(dfs(branch_1),dfs(branch_2), …)

return ans

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the runtime and space complexity of a Recursion problem?

A

Runtime: O(n) where n is the number of nodes in the recursion tree (assuming combine function can be done in constant time)

For Fibonacci:
Runtime = O(2^n)
For merge sort:
MS(arr, left, right) =MS(arr, left, mid), MS(arr, mid+1, right)

T(n) = 2*T(n/2) + O(n): this can be proven to be O(n log n)

Memory: O(h) // height of recursion tree

How well did you know this?
1
Not at all
2
3
4
5
Perfectly