1. Home
  2. Explore
  3. Computer Science
  4. Understanding Recursion

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Understanding Recursion

Speaker 1Speaker 2

Understanding Recursion

16:55
0:00-16:55
  1. Simon

    Welcome to the show. Today we’re building a practical mental model for recursion: what it is, how the call stack makes it work, when it helps, and how it appears in strings, numbers, lists, trees, and graphs. The key idea is less mysterious than it may sound: solve a little of the problem, then call the same method on a smaller or more advanced version of it.

  2. Michael

    Let’s begin with the line-at-an-ATM example. Suppose you want to know how many people are in front of you. The brute-force approach is to walk to the front and count everyone. Recursion offers a different strategy: ask the person ahead of you for their position.

  3. Simon

    And that person can ask the person ahead of them, who asks the next person, and so on. Eventually, the question reaches the first person in line. That person has nobody ahead of them, so their position is one. Then the answer travels backward: each person adds one for themselves and passes the result back.

  4. Michael

    That gives us the two questions behind a recursive solution. First, what smaller problem can I ask the same method to solve? Second, when should the process stop? In the line example, asking about the next person makes progress, and reaching the first person is the stopping condition.

  5. Simon

    In code, that stopping condition is called the base case. A simple line-position method could say: if there is no next person, return one; otherwise, return one plus the position of the next person. The recursive call is the method calling itself, but with an input that moves closer to the base case.

  6. Michael

    That last detail matters. If a recursive call receives exactly the same situation again, with nothing that moves it toward stopping, it can continue indefinitely. A recursive method needs both a meaningful smaller step and a base case it can eventually reach.

  7. Simon

    The essay-revision example shows another pattern. A student revises an essay, submits it, gets feedback, and revises again until the professor accepts it. The essay may be the same object each time, but the work has progressed toward completion. So recursion doesn’t always shrink the object itself; it needs to make progress toward a stopping condition.

  8. Michael

    That leads to a useful definition: recursion is a method calling itself, usually with some parameter or condition that changes the work from one call to the next, until a base case says to stop. Each call can do a small unit of work, delegate a smaller subproblem, or both.

  9. Simon

    There are trade-offs. Recursion can make code elegant and short, especially for data structures that are naturally recursive, such as trees and graphs. It can also replace complicated loops and extra bookkeeping because the call stack provides an implicit stack for managing the work.

  10. Michael

    But method calls have overhead compared with iterating through a loop, and each active recursive call uses space on the call stack. Too many calls can exceed the program’s available stack memory and cause a stack overflow. Recursion can also become unnecessarily complicated if the problem doesn’t divide into sensible subproblems.

  11. Simon

    There can also be an optimization opportunity: if recursive calls repeat the same expensive calculation, caching results can prevent redundant work. We’ll see that with Fibonacci. So choosing recursion means weighing clarity and structure against call overhead, memory use, and the possibility of repeated calculations.

  12. Michael

    To understand why calls wait for one another, picture an interrupted to-do list. You start checking email, your boss sends you to a meeting, then to a board meeting, then to help a colleague. You handle the newest task first, then return to the earlier unfinished tasks in reverse order.

  13. Simon

    That is how the call stack behaves. When method A calls B, A’s work is paused while B runs. If B calls C, B pauses too. Each active method has a stack frame containing information such as its parameters and where its result needs to go. When C finishes, its frame is removed, and B can continue; then B finishes and A resumes.

  14. Michael

    Recursive calls use the same mechanism. A recursive method keeps adding frames until it reaches a base case. Then the calls return in reverse order, each one finishing its waiting work. Without a base case, the stack keeps growing until the program runs out of its allocated stack space.

  15. Simon

    Let’s apply that to reversing a string. We want to return the input characters in reverse order. A minimal base case is the empty string, because reversing it still gives the empty string. A one-character string could also work as a base case, but the empty string is an even smaller input.

  16. Michael

    For the recursive step, take the first character off the front, reverse the rest of the string, and put that first character after the recursive result. For example, with “Hello,” the calls move through “Hello,” “ello,” “llo,” “lo,” “o,” and finally the empty string.

  17. Simon

    Then the calls unwind. The empty string returns first; the call for “o” adds its first character; then the call for “lo” adds its character after that result, and so on. The waiting stack frames keep track of the characters, so the result builds as “olleH.”

  18. Michael

    Notice the two parts of the step: the input gets smaller, and the character we removed is placed after the recursive call. That placement is what reverses the order. The call stack remembers the work to finish, so we don’t need a separate manual stack of characters.

  19. Simon

    A palindrome is a string that reads the same forward and backward. To test one, compare the first and last characters. If they match, continue with the substring between them. If they don’t match, the string cannot be a palindrome, so the method can return false immediately.

  20. Michael

    The base cases are strings of length zero or one. Neither has a pair of characters that can disprove the palindrome property, so both count as palindromes. For a word like “racecar,” the outside characters match, then the next pair matches, and the remaining middle character reaches the base case.

  21. Simon

    If any comparison fails, false returns through the waiting calls and the original call returns false. If every outside pair matches until the middle, true travels back up instead. This example shows recursion can shrink a string from both ends, not only remove one character from the front.

  22. Michael

    Now let’s switch to numbers. To convert a decimal number to binary, repeatedly divide by two, keeping both the quotient and the remainder. The remainder is a binary digit, and dividing the quotient again moves us closer to zero.

  23. Simon

    For example, dividing 233 by two gives a quotient of 116 and a remainder of one. Dividing 116 gives 58 with remainder zero; dividing 58 gives 29 with remainder zero. Continue until the quotient reaches zero, which is the base case.

  24. Michael

    The remainders are produced from the least significant binary digit toward the most significant one. A recursive implementation can arrange the result as calls return, or build a string by prepending each remainder as it divides. The important structure is the same: save the remainder, recurse on a smaller quotient, and stop at zero.

  25. Simon

    Another numeric example is summing the natural numbers from one through n. If n is one, the answer is one, so that’s a base case. For a larger n, add n to the sum from one through n minus one.

  26. Michael

    So the sum up to five becomes five plus the sum up to four, then four plus the sum up to three, and so on until the call for one returns. As the stack unwinds, the pending additions finish: two plus one, then three plus that result, and upward to the original input.

  27. Simon

    This is a good moment to remember that returning from a recursive call doesn’t automatically finish the caller. The caller may still have work waiting, such as adding its number to the returned sum. Each stack frame resumes exactly where it paused.

  28. Michael

    A broader pattern is divide and conquer. Divide a large problem into smaller subproblems, solve those subproblems, and combine their results. The recursive calls handle the smaller pieces; the work after the calls combines them into a solution to the original problem.

  29. Simon

    Binary search is one example. It requires a sorted array. Keep left and right bounds, check the midpoint, and return its index if it holds the target. Otherwise, the sorted order tells you which half could contain the target, so you discard the other half and search within the remaining bounds.

  30. Michael

    Each recursive call changes the bounds to describe a smaller search area. One base case is finding the target. Another stopping condition is running out of a valid range, which means the target wasn’t found. When the target is found, its index is returned through the waiting calls.

  31. Simon

    Fibonacci demonstrates divide and conquer, but also a common problem with a straightforward recursive solution. The sequence is defined so that each value after the initial cases is the sum of the two preceding values. With the usual starting values, the base cases are Fibonacci zero equals zero and Fibonacci one equals one.

  32. Michael

    To compute a later value, the method calls itself for n minus one and n minus two, then adds the results. The first call must finish before its result can be added, and the second call is then evaluated. This creates a branching call structure.

  33. Simon

    The trouble is that the branches repeat work. For example, computing Fibonacci five involves computing Fibonacci three more than once, and smaller values such as Fibonacci two are recalculated as well. As the requested value grows, those repeated subtrees can make the straightforward recursive approach very demanding.

  34. Michael

    Memoization addresses that by caching results. Before calculating a value, check whether it’s already in a map. If it is, return the cached result; if not, calculate it recursively, store it, and then return it. The example uses a hash map, which provides constant-time lookup for cached entries.

  35. Simon

    The base cases can be stored in the cache from the beginning. After that, calls share results because they use the same cache. When another branch needs a value already computed, it can reuse that value instead of building the same recursive work again.

  36. Michael

    Merge sort is another classic divide-and-conquer example. Split an unsorted array into halves, keep splitting until each piece contains just one value, and then merge the pieces back together in sorted order.

  37. Simon

    During a merge, both subarrays are already sorted. Compare their next available values and copy the smaller one into a temporary array. Advance the pointer for the value you copied, and continue while both sides still have values.

  38. Michael

    Once one side runs out, copy the remaining values from the other side. Then copy the merged temporary values back into the corresponding section of the original array. Recursion handles the splitting and the order of subproblems; merging combines the sorted results.

  39. Simon

    The implementation uses start, midpoint, and end indices to describe the section being processed. It recursively sorts the left section first, then the right section, and calls merge for the two sorted sections. A section with no more than one value is already sorted, so it needs no further splitting.

  40. Michael

    That left-first order is a general feature of ordinary sequential recursive calls: the first call must finish before execution moves on to the next one. The stack frames hold the pending work until the smaller sections are ready to merge.

  41. Simon

    Linked lists are another natural fit for recursion. To reverse a singly linked list, recurse through the next pointers until reaching the final node. An empty list or a single node is already reversed, so either can serve as a base case.

  42. Michael

    When the calls return, take the node after the current head and make its next pointer point back to the current head. Then clear the current head’s old next pointer. Clearing that old link matters: otherwise, the reversed links and the old links could form a cycle.

  43. Simon

    The last node returned from the base case is the new head of the reversed list. Each earlier call returns that same new head while changing one link on the way back. So the call stack lets the method travel to the end first, then reverse the pointers while unwinding.

  44. Michael

    A related list problem is merging two sorted linked lists. If one list is empty, return the other one; if the other is empty, return the first. Otherwise compare the two head values, choose the smaller node, and recursively merge the rest.

  45. Simon

    The recursive result becomes the chosen node’s next pointer. The calls continue choosing the smaller available head until one list runs out. Then the base case returns the remainder of the other list, and the chosen nodes link together as the calls unwind.

  46. Michael

    Binary search trees make the recursive structure especially visible. Each node has at most two children, and the values in its left subtree are smaller while values in its right subtree are larger. That ordering rule also holds within each subtree.

  47. Simon

    To insert a value, compare it with the current node. If it’s greater, recurse to the right; if it’s less, recurse to the left. Continue until the chosen child is null, create the new node there, and return the original root so the caller still has the entry point to the tree.

  48. Michael

    For instance, inserting 108 into a tree whose root is 100 takes you right, then compares against the next node. If 108 is smaller than that node, you go left, continuing those comparisons until you reach an empty position. Insertion happens at that leaf position.

  49. Simon

    Another tree task is printing the leaf nodes. A leaf has no left or right child, so print it when you reach one. Otherwise, recursively explore the left subtree and then the right subtree. If a node is null, return because there’s nothing there to print.

  50. Michael

    That traversal is depth first: it explores one branch as far as it can before moving to another. Because the left recursive call happens first, the right subtree waits until the left subtree has been fully explored. The stack records those unfinished branches.

  51. Simon

    Graphs can be explored in a similar way, but they introduce a complication: cycles. A graph can lead back to a node you’ve already seen, so depth-first search keeps a visited set and avoids exploring a node more than once.

  52. Michael

    For each node, first check whether it’s the goal. If it is, return true. Otherwise, inspect its neighbors, skipping any already visited and marking new ones as visited before exploring them. If a recursive search through a neighbor finds the goal, return true; if every reachable neighbor has been explored without success, return false.

  53. Simon

    That order explains the name depth-first search: after choosing a neighbor, follow that path deeper before returning to explore another neighbor. The visited set prevents cycles from sending the search around repeatedly.

  54. Michael

    We should also distinguish memoization from tail-call optimization. Memoization reuses previously calculated answers. Tail-call optimization, when a language supports it, aims to avoid keeping as many recursive stack frames by recognizing a particular form of recursive call.

  55. Simon

    A call is tail recursive when the recursive call is the final result of the method, with no additional work waiting after it. In a basic factorial example, returning the current value multiplied by a recursive call is not tail recursive, because multiplication remains to be done after that call returns.

  56. Michael

    The example transforms that pattern by passing along an accumulated result. Then the method can return just the recursive call, making it eligible for tail-call optimization in languages whose compilers support it. Support varies: the technique is common in functional languages, but it isn’t inherent across languages such as Python, Java, or JavaScript.

  57. Simon

    So the practical rule is to check the language and compiler rather than assume tail calls will prevent stack growth. And even when recursion is elegant, the base case, progress toward it, and stack use still deserve careful attention.

  58. Michael

    The central blueprint holds across all these examples: identify the smallest case that can be answered directly, make a recursive call that progresses toward it, and decide what work happens as calls return. Strings, numbers, linked lists, trees, and graph searches all use that structure in different ways.

  59. Simon

    And when the problem divides into subproblems, ask whether their results need to be combined, as in merge sort, or whether the same subproblem might be repeated, as in Fibonacci. Those questions help you decide how to structure the recursion and whether caching or another technique could help.

  60. Michael

    A natural next step is backtracking: recursively explore a decision space, recognize when a choice doesn’t work, and return to try another path. That builds on the same ideas we’ve covered—recursive calls, stopping conditions, and the way the call stack preserves the choices still waiting to be explored.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent