Recursion Basics Resource - aloalgo

Recursion Basics

Recursion is when a function calls itself. It's a powerful technique for solving problems that can be broken down into smaller, similar subproblems.

The Two Parts of Recursion

Every recursive function needs:
  1. Base case: When to stop (prevents infinite recursion)
  2. Recursive case: How to break down the problem

Visualizing the Call Stack

Common Patterns

Linear Recursion

Binary Recursion (Two Branches)

Tree Recursion (Multiple Branches)

Recursion vs Iteration

Tail Recursion

When the recursive call is the last operation, it's called tail recursion. Some languages optimize this, but Python does not.

Common Mistakes

When to Use Recursion

  • Tree/graph traversal: Naturally recursive structures
  • Divide and conquer: Merge sort, quick sort
  • Backtracking: Exploring all possibilities
  • Dynamic programming: Breaking into subproblems
  • Nested structures: Parsing, nested lists

Tips for Recursive Thinking

  1. Trust the recursion: Assume the recursive call works correctly
  2. Focus on one level: What does THIS call do?
  3. Identify the subproblem: What's the smaller version?
  4. Define base cases first: When is the answer obvious?

Time and Space Complexity

PatternTimeSpace (Stack)
Linear (factorial)O(n)O(n)
Binary (fibonacci)O(2ⁿ)O(n)
Tree traversalO(n)O(h)*
Divide & conquerO(n log n)**O(log n)
*h = height of tree (log n for balanced, n for skewed)
**For merge sort; varies by algorithm

Common Interview Tips

  1. Always state base case first: Write and explain the base case before the recursive case.
  2. Trace through small examples: Walk through your recursion with n=0, n=1, n=2 to verify correctness.
  3. Consider stack overflow: For deep recursion (n > 1000), mention potential stack issues and iterative alternatives.
  4. Know when to iterate: Simple linear problems are often cleaner with loops.
Was this helpful?
© 2026 aloalgo. All rights reserved.