Grokking Algorithm Complexity and Big-O
Ask Author
Back to course home

0% completed

Vote For New Content
Quiz
On this page
Question 1
What is the time complexity of the following recursive function?
public void printNumbers(int n) {
    if (n == 0) return;
    System.out.println(n);
    printNumbers(n - 1);
}
A
O(1)
B
O(n)
C
O(n2)
D
O(log n)
Question 2
What is the space complexity of the following recursive function?
public int factorial(int n) {
    if (n == 0) return 1;
    return n * factorial(n - 1);
}
A
O(1)
B
O(log n)
C
O(n)
D
O(n2)
Question 3
Analyze the time complexity of the following code:
public int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}
A
O(n)
B
O(n2)
C
O(2n)
D
O(log n)
Question 4
What is the space complexity of the following recursive function using memoization?
import java.util.HashMap;

public class Solution {
    private HashMap<Integer, Integer> memo = new HashMap<>();

    public int fib(int n) {
        if (n <= 1) return n;
        if (memo.containsKey(n)) return memo.get(n);

        int result = fib(n - 1) + fib(n - 2);
        memo.put(n, result);
        return result;
    }
}
A
O(1)
B
O(n log n)
C
O(n2)
D
O(n)
Question 5
What is the time complexity of the following recursive function?
public void nestedRecursion(int n) {
    if (n <= 0) return;
    nestedRecursion(n - 1);
    nestedRecursion(n - 1);
}

A
O(n)
B
O(2n)
C
O(n2)
D
O(logn)
Question 6
Analyze the space complexity of the following function:
public int power(int x, int n) {
    if (n == 0) return 1;
    int temp = power(x, n / 2);
    if (n % 2 == 0) {
        return temp * temp;
    } else {
        return x * temp * temp;
    }
}
A
O(n)
B
O(log n)
C
O(1)
D
O(n2)
Question 7
What is the time complexity of the following recursive function?
public void printPattern(int n) {
    if (n == 0) return;
    for (int i = 0; i < n; i++) {
        System.out.print("*");
    }
    System.out.println();
    printPattern(n - 1);
}
A
O(n)
B
O(2n)
C
O(logn)
D
O(n2)
Question 8
What is the time complexity of the following recursive function that calculates the depth of a binary tree?
public int sumOfNodes(TreeNode root) {
        if (root == null) return 0;
        return root.val + sumOfNodes(root.left) + sumOfNodes(root.right);
 }
A
O(n)
B
O(log n)
C
O(n2)
D
O(2n)

.....

.....

.....

Like the course? Get enrolled and start learning!

On this page