Skip to main content

πŸ” Recursion

One-line summary: Solve a problem by breaking it into smaller instances of itself β€” the foundation of DFS, divide-and-conquer, backtracking, and tree algorithms.


Diagram​

Recursion Overview Recursion GIF

Concept​

Every recursive function needs:

  1. Base case β€” stops the recursion.
  2. Recursive case β€” reduces the problem toward the base case.
  3. Trust the recursion β€” assume the recursive call returns the correct answer.

Common Patterns​

Factorial​

function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}

Fibonacci (memoised)​

function fib(n, memo = {}) {
if (n <= 1) return n;
if (memo[n]) return memo[n];
return (memo[n] = fib(n - 1, memo) + fib(n - 2, memo));
}

Power (fast exponentiation)​

function power(base, exp) {
if (exp === 0) return 1;
if (exp % 2 === 0) {
const half = power(base, exp / 2);
return half * half;
}
return base * power(base, exp - 1);
}

Pitfalls​

  • Missing base case β†’ infinite recursion / stack overflow
  • Redundant subproblem calls β†’ add memoisation
  • Deep recursion in JS β†’ stack size ~10k; consider iterative with explicit stack

Practice Problems​

ProblemDifficultySolution
LC 231 β€” Power of TwoEasy
LC 110 β€” Balanced Binary TreeEasy
LC 24 β€” Swap Nodes in PairsMedium
LC 344 β€” Reverse StringEasy
LC 509 β€” Fibonacci NumberEasy
LC 326 β€” Power of ThreeEasy
LC 779 β€” K-th Symbol in GrammarMedium
LC 95 β€” Unique Binary Search Trees IIMedium
LC 894 β€” All Possible Full Binary TreesMedium
CC β€” RecamΓ‘n Sequence (RECAMAN)Easy
LC 241 β€” Different Ways to Add ParenthesesMedium
LC 21 β€” Merge Two Sorted ListsEasy
LC 50 β€” Pow(x, n)Medium
LC 70 β€” Climbing StairsEasy
LC 104 β€” Maximum Depth of Binary TreeEasy
LC 111 β€” Minimum Depth of Binary TreeEasy
LC 206 β€” Reverse Linked ListEasy
LC 226 β€” Invert Binary TreeEasy
LC 234 β€” Palindrome Linked ListEasy
LC 342 β€” Power of FourEasy
LC 372 β€” Super PowMedium
LC 390 β€” Elimination GameMedium
LC 486 β€” Predict the WinnerMedium
LC 687 β€” Longest Univalue PathMedium
LC 698 β€” Partition to K Equal Sum SubsetsMedium
LC 700 β€” Search in a Binary Search TreeEasy
LC 701 β€” Insert into a Binary Search TreeMedium
LC 1137 β€” N-th Tribonacci NumberEasy
LC 1342 β€” Number of Steps to Reduce to ZeroEasy
LC 1545 β€” Find Kth Bit in Nth Binary StringMedium
CC β€” Factorial (FACT)Easy
CC β€” Tower of Hanoi (HANOI)Medium
CC β€” Recursive Function (RECFUNC)Easy

← Back to Home Β· Β© sparshjaswal