Recursion Flashcards

1
Q

Time complexity formula for recursive code?

A

Simple case with one branch:
O(number of recursive calls * work per recursive call)
Complex case:
O(branching_factor^max_depth(height) * work per recursive call)
Proportional to # leaf nodes in
complete tree

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

Space complexity for recursive code?

A

O(depth_of_recursion * space_per_recursive_call)

Proportional to the depth of the recursion

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

What are 6 recursive patterns?

A
  1. Iteration
  2. Breaking into sub problems
  3. Selection(combination)
  4. Ordering(Permutation)
  5. Divide and conquer
  6. Depth first search
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

3 ways to return results from recursive function?

A
  1. Store the result to global variable
  2. Store the result to a passed variable
  3. Build up the result as we return.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

In recursive function , can we reassign a reference and expect it to propagate back to the call stack?

A

No

https://stackoverflow.com/questions/7848312/recursive-pass-in-object-by-reference-java

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

How to Implement pow(x, n), which calculates x raised to the power n (i.e. xn).

A
public double MyPow(double x, int n)
        {
            long pow = n;
            if (n < 0)
            {
                x = 1 / x;
                pow = -pow;
            }
            return Helper(x, pow);
        }      
    private double Helper(double x, long n)
    {
        if (n == 0)
            return 1;
        if (n == 1)  //! power of 1 of any number is equal to that number 
            return x;

        if (n % 2 == 0) 
            return Helper(x * x, n / 2);            
        else 
            return x * Helper(x * x, n / 2);
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to implement gcd recursively ?

A
public static int gcd(int a, int b) {
if (b > a) return gcd(b, a);
if (b == 0) return a;
return gcd(b, a % b);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly