Logo
Logo
Home
Archive
AI Agent Notes
Advertise
YouTube
Login
Sign Up
Logo
  • Home
  • Posts
  • 🦥Recursion For Dummies

🦥Recursion For Dummies

Feb 12, 2025

Hello friends!

Welcome to this week’s Sloth Bytes!

I hope you had a great week.

Never explain another bug with Jam AI.

Say goodbye to vague bug reports.

Jam turns any bug into a complete technical report in one click.

  • Records issue & auto-generates technical description

  • Creates step-by-step reproduction guide

  • Captures all debug essentials (console, network, environment)

  • Integrates with Jira, GitHub, Linear & more

  • Join 140K+ developers who fixed the bug reporting bottleneck.

One click. Perfect bug reports. Every time.

Stop wasting time collecting repro details - get Jam free today.

Try It For Free

Sloths have small brains.

Gif by MVG on Giphy

HOWEVER, scientists are now realizing that this actually doesn’t relate to intelligence at all.

The brains of sloths might be small but they are very much focused on the specific skills that they need for survival.

Recursion: It's Not as Scary as You Think

Ever been told "just use recursion" and felt your brain melt? Let me simplify this concept with some simple examples.

What is Recursion?

Think of it like those Russian nesting dolls:

Gif by cecymeade on Giphy

  • Each doll contains a smaller version of itself

  • Until you reach the smallest doll

  • That's it. That's recursion.

In programming, recursion is when a function solves a problem by calling itself (directly or indirectly) on a smaller/simpler version of that problem until it reaches a stopping condition.

Why Use It?

Recursion is especially natural for problems whose structure is recursive already:

  • Trees and nested structures

  • Divide-and-conquer algorithms

  • Backtracking/search problems

  • Directories, ASTs, JSON-like nested data, and graphs (with cycle handling)

  • Problems that break into smaller instances of the same problem

The 2 Steps of Recursion

Every recursive function needs:

  1. A base case (when to stop)

  2. A recursive case (when to continue)

Those are the two ingredients, but there is one more question you always need to ask: does each recursive call actually make progress toward the base case? A base case that is unreachable is just an infinite loop wearing a fancy hat.

Example

Calculating a factorial (5! = 5 × 4 × 3 × 2 × 1)

// Iterative version — simple and efficient here
function factorialIterative(n) {
  if (!Number.isInteger(n) || n < 0) {
    throw new Error('factorial expects a non-negative integer');
  }

  let result = 1;
  for (let i = 2; i 

What’s happening?

factorial(5) breaks down like this:

factorial(5)
→ 5 * factorial(4)
  → 4 * factorial(3)
    → 3 * factorial(2)
      → 2 * factorial(1)
        → 1 // We hit our Base case! Let's go back and add it up.
      ← 2 * 1 = 2 // 2 * factorial(1), factorial(1) = 1
    ← 3 * 2 = 6 // 3 * factorial(2), factorial(2) = 2
  ← 4 * 6 = 24 // 4 * factorial(3), factorial(3) = 6
← 5 * 24 = 120 // 5 * factorial(4), factorial(4) = 24

The call stack is the hidden cost

Each normal recursive call usually creates a new stack frame containing things like parameters, local variables, and where execution should return afterward.

So a recursive algorithm can use O(depth) extra stack space even when the equivalent loop uses O(1) auxiliary stack space. If the recursion becomes too deep, many runtimes throw a stack-overflow/recursion-depth error.

Some languages/runtimes optimize certain tail calls, but you should not assume tail-call optimization exists unless your language/runtime guarantees it.

Common Use Cases

  1. Tree/nested traversal

    • File-system trees

    • DOM/AST/JSON trees

    • Tree search and transformations

  2. Divide and conquer

    • Merge sort

    • Quicksort

    • Recursive binary-tree algorithms

  3. Backtracking

    • Mazes

    • Permutations/combinations

    • Constraint-search problems

  4. Dynamic programming with memoization

    • Recursive definitions with overlapping subproblems can be cached so the same state is not recomputed repeatedly.

Recursion can accidentally explode

The classic bad example is naive Fibonacci:

function fib(n) {
  if (n 

This recomputes the same values over and over, producing exponential work. Adding memoization (cache results by input/state) can reduce many overlapping-subproblem recursions dramatically.

The lesson is not “recursion is slow.” The lesson is: analyze the recurrence/call tree. A clean-looking recursive function can still duplicate enormous amounts of work.

When Not to Use It

  • A loop is simpler and clearer for the problem

  • Recursion depth can grow with untrusted or extremely large input

  • The runtime has a small/strict call-stack limit

  • You need tight control over memory or latency

  • An explicit stack/queue makes traversal state easier to manage

Quick Tips

  1. Define a base case that handles every terminal state you expect

  2. Make sure each call moves toward that base case

  3. Track the maximum recursion depth

  4. Draw the call tree for small inputs

  5. Watch for overlapping subproblems; memoize when appropriate

  6. If inputs can create cycles (graphs/directories with links), keep a visited set

  7. Use iteration when it is simpler—recursion is a tool, not a badge of honor

Remember

  • Recursion solves a problem in terms of smaller instances of itself

  • A reachable stopping condition is mandatory

  • Recursive calls consume stack space unless optimized away

  • Time complexity comes from the full call tree, not the number of lines in the function

  • Memoization can eliminate repeated subproblems

  • Iteration and recursion can often express the same algorithm—pick the clearer/safest form for your constraints

If you want to keep learning

  • Data structures and algorithms explained — recursion shows up constantly in trees, graphs, divide-and-conquer algorithms, and interview problems.

  • Big O notation explained — learn how recursive calls affect time complexity and stack-space usage.

  • Debugging techniques — recursive code gets confusing fast when the base case or call stack goes sideways.

The all new le Chat: Your AI assistant for life and work (6 minute read)

Mistral released their own AI chat app!

Lyft and Claude Partnership (2 minute read)

Anthropic is an AI safety and research company that's working to build reliable, interpretable, and steerable AI systems.

Google starts testing new Search 'AI Mode' internally – Here’s an early look at it (3 minute read)

Google Search is working on a new “AI Mode” that offers a “persistent place” to ask more “open-ended / exploratory questions.”

Inside the Duolingo Company Handbook (15 minute read)

Learn about Duolingo's culture, principles, and approach to building extraordinary things.

How I learned to code with my voice (14 minute read)

Struggling with severe hand pain, I learned to code by voice. This is my journey with Talon and Cursorless, plus practical tips for hands-free development.

Thank you to everyone who submitted 😃 

GabrielDornelas, E-Sieben, levi-manoel, TheTigerPython, RelyingEarth87, SDKwapis, porrrq, and nhillemann.

Remove the Computer Virus

Your computer might have been infected by a virus! Create a function that finds the viruses in files and removes them from your computer.

Examples

remove_virus("PC Files: spotifysetup.exe, virus.exe, dog.jpg")
output = "PC Files: spotifysetup.exe, dog.jpg"

remove_virus("PC Files: antivirus.exe, cat.pdf, lethalmalware.exe, dangerousvirus.exe ")
output = "PC Files: antivirus.exe, cat.pdf"

remove_virus("PC Files: notvirus.exe, funnycat.gif")
output = "PC Files: notvirus.exe, funnycat.gif")

Notes

  • Bad files will contain "virus" or "malware", but "antivirus" and "notvirus" will not be viruses.

  • Return "PC Files: Empty" if there are no files left on the computer.

How To Submit Answers

Reply with

  • A link to your solution (github, twitter, personal blog, portfolio, replit, etc)

  • or if you’re on the web version leave a comment!

  • If you want to be mentioned here, I’d prefer if you sent a GitHub link or Replit!

Working on the next video and uh yeah that’s about it.

That’s all from me!

Have a great week, be safe, make good choices, and have fun coding.

If I made a mistake or you have any questions, feel free to comment below or reply to the email!

See you all next week.

Keep Reading

Read all
arrow-right
envelope-simple

Join 50k+ developers and become a better programmer and stay up to date in just 5 minutes.

© 2026 Sloth Bytes.
beehiivPowered by beehiiv