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);
β οΈ 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);
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)