Recursion Fundamentals

Write recursive functions with clear base cases, understand the call stack, and recognise the pick or not-pick pattern used everywhere later.

Beginner · about 6 hours · difficulty 2/5

Learn first: Time and Space Complexity

Recursion is the foundation for trees, graphs, backtracking and DP. If recursion feels shaky, every later topic will too.

How to think

  • Define what the function returns for a given input, in one sentence.
  • Write the base case first.
  • Assume the function works for smaller inputs (the leap of faith) and combine the results.
  • Draw the recursion tree for small inputs to see the number of calls and the stack depth.

Core patterns

  • Linear recursion: factorial, sum of digits, reverse an array, check palindrome.
  • Divide and conquer: power(x, n) in O(log n), merge sort.
  • Pick or not pick: at each index, include the element or skip it. This generates all subsequences and later becomes subset-sum DP.
  • Return values vs global state: count subsequences with sum k by returning counts instead of mutating a global.

Classic problems

Pow(x, n), Print all subsequences, Count subsequences with sum K, Generate Parentheses, Tower of Hanoi, Fibonacci (then see why it is O(2^n)), Reverse a stack using recursion, Sort a stack using recursion.

Pitfalls

  • Missing or wrong base case causing stack overflow.
  • Deep recursion (depth 1e5 or more) crashing; know when to go iterative.
  • Passing large structures by value at every call.

You are ready to move on when you can draw the recursion tree for printing all subsequences of [1, 2, 3] and state its time complexity.

Key concepts

  • Base case and recursive case
  • Call stack and stack depth
  • Recursion trees
  • Pick or not-pick pattern
  • Divide and conquer
  • Tail recursion and iteration

Mini project

Solve these 10 in 7 days without loops where possible, log time and pattern: Factorial, Reverse an array, Check palindrome, Pow(x, n), Print all subsequences, Count subsequences with sum K, Generate Parentheses, Tower of Hanoi, Reverse a stack using recursion, Sort a stack using recursion.

Check yourself

How many calls does the pick or not-pick recursion make for an array of size n, and how deep does the stack go?

Free resources