POST 1 of 5 MorningDSAConcept
Recursion is just a function calling itself
Day 22. Week four begins. We open with the topic that every CS-101 student claims to understand and most production developers misuse — recursion. The definition is small. A recursive function is a function that calls itself. That's it. Strip away the formalism and you're left with two requirements every recursive function must have. One — a base case. The simplest input where the function returns a direct answer without further recursion. Without a base case, the function calls itself forever and you get a stack overflow. Two — a recursive case. The function reduces the input to a smaller version of the same problem and calls itself with that smaller input. The smaller call returns; you combine its result with whatever local work you needed. The call stack does the bookkeeping. Each call gets its own stack frame with its own local variables. When a call returns, its frame is popped off the stack. The recursion depth equals the number of frames on the stack at peak. When does recursion fit naturally? When the problem can be described as 'solve a smaller version of the same problem'. Tree traversal — the answer for a tree is the answer for the left subtree, plus the answer for the right subtree, plus something at the root. Trivially recursive. Divide-and-conquer algorithms — mergesort, quicksort, fast Fourier transform. Same recursive shape. When does it NOT fit? Iterative state machines, where you walk through stages with a fixed transition table. Use a loop. Deep recursive structures with no memoisation, where exponential branching makes the runtime explode. Add memoisation (Day 27 DP) or convert to iteration. The rule — recursion is a thinking tool. Use it to UNDERSTAND a problem. Convert to iteration when the production code needs to be deeper than Python's stack allows.
#DSA#Algorithms#Python#100DaysOfCode#CodingInterview#Recursion