Data Structures & AlgorithmsHardProduct-company MCQ pattern

What is the time complexity of solve(n)?

What is the time complexity of solve(n)?
def solve(n):
    if n <= 0:
        return
    for i in range(n):
        pass          # O(1) work
    solve(n - 1)
  1. A. O(2ⁿ)
  2. B. O(n)
  3. C. O(n log n)
  4. D. O(n²)

Correct answer: D. O(n²)

T(n) = T(n − 1) + n, so the loop runs n + (n − 1) + … + 1 = n(n + 1)/2 times (5050 for n = 100): O(n²). O(n) counts only the recursion depth, and O(2ⁿ) would need two recursive calls.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic