Algorithm Thinking

Making complex problems structurally simple.

Structural Decomposition โ€” Recursion

Recursion is not magic. It is structural decomposition.

If a problem looks like a smaller version of itself, recursion is often the cleanest model.


๐Ÿง  Why Recursion Feels Hard

Because you cannot "see" the stack.

Iteration feels mechanical. Recursion feels abstract.

The fear is not recursion. The fear is invisible memory growth.


๐Ÿ” What Recursion Actually Is

A function that solves a problem by delegating to a smaller instance of the same problem.

Without a base case โ†’ infinite recursion โ†’ stack overflow.


Simple Example โ€” Factorial

function factorial(n: number): number {
  if (n === 0) return 1
  return n * factorial(n - 1)
}

Time: O(n)

Space: O(n)

Depth equals memory growth.


โš ๏ธ Where Recursion Breaks โ€” Fibonacci

function fib(n: number): number {
  if (n <= 1) return n
  return fib(n - 1) + fib(n - 2)
}

Time: O(2โฟ)

The issue is not recursion. The issue is repeated subproblems.


๐Ÿงฑ Structural Fix โ€” Memoization

function fibMemo(n: number, memo = new Map<number, number>()): number {
  if (n <= 1) return n
  if (memo.has(n)) return memo.get(n)!

  const value = fibMemo(n - 1, memo) + fibMemo(n - 2, memo)
  memo.set(n, value)

  return value
}

Time: O(n)

Space: O(n)

Memoization transforms exponential growth into linear growth โ€” this is a structural shift, not a trick.


๐Ÿง  State & Transitions

Many recursive problems are not about calling a function again. They are about defining state correctly.

State is the minimal information needed to describe where you are in the problem.

Once state is defined clearly, transitions become mechanical.

Most recursion mistakes come from unclear state definition, not from the recursion itself.


๐ŸŒณ Trees โ€” Where Recursion Feels Natural

Trees are recursively defined structures.

Each subtree is itself a tree. Recursion mirrors the structure itself.

function invertTree(root: TreeNode | null): TreeNode | null {
  if (!root) return null

  const temp = root.left
  root.left = root.right
  root.right = temp

  invertTree(root.left)
  invertTree(root.right)

  return root
}

Time: O(n)

Space: O(h)


โš–๏ธ Recursion vs Iteration

Clarity and control are trade-offs. Choose deliberately.


๐Ÿงญ Panic Reset Strategy


๐Ÿง  Mental Model Summary


Final Insight

Recursion is not about cleverness.

It is about expressing structure clearly and defining state precisely.