0
0
DSA Typescriptprogramming~3 mins

Why Recursion Exists and What Loops Cannot Express Cleanly in DSA Typescript - The Real Reason

Choose your learning style9 modes available
The Big Idea

Discover why some problems just can't be solved well with loops alone and how recursion unlocks their secrets!

The Scenario

Imagine you want to find the total number of files inside folders, including all subfolders, on your computer. You try to count them by opening each folder one by one and adding up the files manually.

The Problem

This manual counting is slow and confusing because folders can have many layers of subfolders. Using simple loops, you can only go through one level at a time, making it hard to handle folders inside folders without repeating code or getting lost.

The Solution

Recursion lets you solve this by having a function call itself to handle each subfolder. This way, you can cleanly explore all layers of folders without complicated loops or extra tracking, making the code simpler and easier to understand.

Before vs After
Before
let totalFiles = 0;
for (let i = 0; i < folders.length; i++) {
  totalFiles += folders[i].files.length;
  for (let j = 0; j < folders[i].subfolders.length; j++) {
    totalFiles += folders[i].subfolders[j].files.length;
  }
}
After
function countFiles(folder) {
  let count = folder.files.length;
  for (const subfolder of folder.subfolders) {
    count += countFiles(subfolder);
  }
  return count;
}
What It Enables

Recursion enables you to elegantly solve problems with repeating patterns inside themselves, like nested folders or branching paths, which loops alone struggle to express clearly.

Real Life Example

Calculating the total number of comments and replies in a social media post, where replies can have replies inside them, is a perfect example where recursion shines.

Key Takeaways

Manual looping struggles with nested or self-similar structures.

Recursion uses self-calling functions to handle these nested layers cleanly.

This makes code simpler, easier to read, and less error-prone for complex problems.