DEV Community

Laxman Nemane
Laxman Nemane

Posted on

πŸš€ Today I Learned the Most Amazing DSA Concept β€” Recursion!

Hey friends,
Today was mind-blowing 🀯 because I learned something in DSA that feels like magic β€” Recursion.

It’s actually very simple… but at first, you might not fully get it. That’s okay! Keep practicing and one day, it will just click.

πŸ” What is Recursion?
Recursion is when a function calls itself using its own definition.

There are two most important parts of recursion:

Base Case β†’ This stops the recursion (very important 🚨).
Recursive Call β†’ Where the function calls itself again.

🧠 A Real-Life Example
Imagine a queue of 6 people: A, B, C, D, E, F.

A doesn’t know how many people are behind him, so he asks B.

B doesn’t know either, so he asks C.

This continues until F.

F says, β€œNobody is behind me!” (Base Case).

Then the answer comes back step-by-step to A.

That’s how recursion flows β€” going deep until a base case, then returning back.

πŸ’‘ Fun Fact
If you type recursion in Google, it will say:
Did you mean: recursion?
Click it… and it will suggest recursion again. Infinite loop! πŸ˜‚ Google is trolling us but also teaching recursion in a fun way.

πŸ–₯ Simple Programming Example
javascript


function fn(n) {
    console.log("Lakhan");
    n = n - 1;
    fn(n); // Recursive Call
}

fn(5);
Enter fullscreen mode Exit fullscreen mode

⚠️ This will keep going forever and crash with Stack Overflow because there’s no base case.

βœ… Correct Way with Base Case
javascript


function fn(n) {
    if (n === 0) return; // Base Case - stops recursion
    console.log("Lakhan");
    fn(n - 1); // Recursive Call
}

fn(5);
Enter fullscreen mode Exit fullscreen mode

Now it prints "Lakhan" 5 times and stops.

πŸ— How It Works in Call Stack
fn(5) calls fn(4) (fn(5) is paused until fn(4) finishes)

fn(4) calls fn(3)

… and so on, until fn(0) hits the base case.

Then functions start returning one by one.

❌ Common Mistakes to Avoid
❌ Missing base case β†’ Infinite loop!
❌ Not simplifying input (always do n-1, n+1, etc.)
❌ Deep recursion with huge input β†’ May crash or freeze
❌ Ignoring time complexity

⏳ Time Complexity
For most simple recursive functions like above, the time complexity is O(n) β€” similar to a loop because the code block runs n times.

πŸ’¬ Final Tip β†’
Always put the base case at the top and think about how the input changes with each call. Practice daily, and one day recursion will feel as natural as loops.

Keep practicing and keep coding! πŸš€

Top comments (0)