Understanding Recursion
Recursion: Concepts, Patterns, and Applications
What recursion is
Recursion is a problem-solving technique in which a function calls itself to solve smaller instances of the same problem. Each call should make progress toward a stopping condition; when that condition is reached, the calls return and their results are combined or passed back.
A recursive solution usually has two essential parts:
Base case: A condition under which the function stops making recursive calls and returns a direct result.
Recursive case: A step that performs a small amount of work and calls the function again on a smaller or simpler version of the problem.
A recursive function is useful when a large problem can be reduced to smaller instances of the same problem, until an instance is simple enough to solve directly.
Example: finding a position in a line
Suppose someone wants to know their position in a line. Instead of counting every person from the front, they can ask the person ahead of them for their position. That person asks the person ahead of them, and so on.
The process stops at the first person in line, whose position is known directly: first. Then the answer moves back through the line:
The person behind the first person is in position 2.
The next person is in position 3.
Each person adds 1 to the position reported by the person ahead.
The recursive structure is:
Base case: If there is no person ahead, the current person is first.
Recursive case: The current person’s position is 1 plus the position of the person ahead.
The same idea can be represented with a function such as position(person): if the next person is absent, return 1; otherwise, return 1+position(next person).
The important point is that each call advances to a different person. It does not repeat the exact same problem unchanged.
Example: revising an essay
An essay may be revised repeatedly until it meets a required standard. Each round makes progress, even though the same essay is being worked on.
Base case: The essay needs no more revisions.
Recursive case: Revise the essay, then check it again.
This example shows that the input object does not always need to be replaced with a different object. Progress can also come from changing the object’s state so that it is closer to completion.
The call stack
When a function is called, a program records information about that call in a stack frame. A frame typically stores details such as the function’s parameters, local variables, and where execution should resume after the call finishes.
The call stack is the stack of active function calls. It follows a last-in, first-out order:
A function begins executing.
If it calls another function, the new call is placed on top of the stack.
The current function pauses until the called function returns.
When the call at the top returns, its frame is removed, and execution resumes in the previous frame.
For example, if function A calls B, and B calls C, then C must return before B can finish, and B must return before A can finish. This is why recursive calls often build up first and then resolve in reverse order.
Why recursion needs a base case
If each call makes another call without ever reaching a stopping condition, stack frames continue to accumulate. Eventually, the program may exceed its available call-stack memory and produce a stack overflow.
A base case prevents that uncontrolled growth. Once a call reaches the base case, it returns instead of creating another recursive call. That return allows earlier frames to resume and eventually finish.
Recursion is therefore not magic and does not restart the entire program from the beginning. Each call has its own frame and paused state. The stack remembers what each call still needs to do.
Benefits and trade-offs
Recursion can make some problems easier to express, especially when the problem itself has a recursive structure.
Advantages
Clear problem structure: A recursive function can closely match the definition of a problem.
Less explicit bookkeeping: The call stack keeps track of pending work, reducing the need for manually managed stacks or complicated loop state.
Concise traversal: Tree and graph traversals often become short and readable because each subtree or neighbor can be handled with the same logic.
Useful optimization patterns: Recursive solutions can use techniques such as memoization to avoid repeating expensive work.
Disadvantages
Call overhead: Each function call has some runtime cost, so a recursive version can be slower than an equivalent loop.
Memory use: Each active call requires a stack frame. Deep recursion can consume substantial memory or cause a stack overflow.
Repeated computation: A recursive definition may solve the same subproblem many times, as happens in the basic Fibonacci implementation.
Added complexity when used unnecessarily: A recursive solution is not automatically clearer. If a problem does not divide naturally into smaller versions of itself, recursion may make the solution harder to understand.
Recursion is especially suitable for recursively structured data, such as trees, nested objects, and some graph algorithms. The best choice depends on how naturally the problem divides and on the language’s support for recursion.
Recursion with strings
Strings are made of characters, so a recursive algorithm can often reduce a string one character at a time. The input becomes smaller with each call, while the call stack preserves information needed to finish the result.
Reversing a string
To reverse a string recursively:
Base case: The empty string reverses to itself.
Recursive case: Reverse everything after the first character, then append the first character to the end.
If the input is hello, the calls successively work with hello, ello, llo, lo, o, and finally the empty string. When the calls return, the saved first characters are appended in reverse order:
The empty string returns as the empty string.
The call for
oreturnso.The call for
loreturnsol.The call for
lloreturnsoll.The call for
elloreturnsolle.The original call returns
olleh.
The first character does not need to be stored in a separate explicit stack: each suspended function frame retains it until the recursive call finishes.
Checking whether a string is a palindrome
A palindrome reads the same forward and backward. A recursive check compares the characters at the two ends of the current substring.
Base case: A string of length 0 or 1 is a palindrome because no mismatched pair exists.
Failure case: If the first and last characters differ, the string is not a palindrome.
Recursive case: If the two characters match, check the substring between them.
For example, racecar is checked by comparing its outer characters, then the next pair inward, until only the middle character remains. If any pair differs, the algorithm can immediately return false. Otherwise, the base case eventually returns true, and that result passes back through the earlier calls.
Recursion with numbers
Converting a decimal number to binary
Binary represents numbers using the digits 0 and 1. Repeated division by 2 produces the binary digits as remainders:
Divide the current number by 2 using integer division.
Record the remainder.
Repeat with the quotient.
Stop when the quotient reaches 0.
For example, the process for 233 begins:
233 divided by 2 gives quotient 116 and remainder 1.
116 gives quotient 58 and remainder 0.
58 gives quotient 29 and remainder 0.
The process continues until the quotient is 0.
The remainders are produced from least significant digit to most significant digit. A recursive function can build the final binary string by prepending each remainder to the result of the recursive call on the quotient. The output for 233 is 11101001.
A possible structure is:
Base case: If the current number is 0, return the empty string.
Recursive case: Compute the remainder modulo 2, recursively convert the integer quotient, and place the remainder before the recursive result.
The changing input—the quotient—gets smaller on each call, so it progresses toward the base case.
Summing the natural numbers up to n
The sum from 1 through n can be defined recursively:
Base case: The sum through 1 is 1.
Recursive case: The sum through n is n plus the sum through n−1.
For instance, the sum through 5 becomes 5+4+3+2+1=15. The calls descend from 5 to 1, then return upward while adding each saved value.
More generally, for positive integer n:
The recursive version uses O(n) time and O(n) call-stack space. An iterative loop can calculate the same sum with constant extra space.
Divide-and-conquer algorithms
Divide and conquer solves a problem by dividing it into smaller subproblems, solving those subproblems, and combining their results. It commonly uses recursion because each subproblem is another instance of the original problem.
The general process is:
Divide the original problem into smaller parts.
Solve each part, often recursively.
Combine the subproblem results into a solution to the original problem.
Binary search
Binary search finds a target in a sorted array by repeatedly discarding half of the remaining search interval. The array must be sorted for the comparisons to justify discarding either half.
The algorithm maintains a left and right boundary:
Find the midpoint of the current interval.
If the midpoint contains the target, return its index.
If the target is smaller, continue in the left half.
If the target is larger, continue in the right half.
If the interval becomes empty, the target is not present.
In a recursive implementation, the bounds change on each call. If the target is greater than the midpoint value, the next interval begins just after the midpoint. If it is smaller, the next interval ends just before the midpoint.
Because each step halves the search space, binary search takes O(logn) time for an array of length n. A recursive version uses O(logn) call-stack space. An iterative version can use O(1) extra space.
Fibonacci numbers and repeated work
The Fibonacci sequence is defined by adding the two preceding values. With the common starting values F(0)=0 and F(1)=1:
A direct recursive implementation follows this definition: it calculates F(n−1) and F(n−2), then adds the results.
The difficulty is that many subproblems are repeated. For example, calculating F(5) requires calculating F(3) as part of the F(4) calculation and then calculating F(3) again as the other part of the original call. Each repeated call may itself repeat many more calculations. The basic recursive version therefore has exponential running time, often described as O(2n), and its call stack can grow to O(n) depth.
This example demonstrates that a recursive definition may be elegant but inefficient if it repeatedly solves identical subproblems.
Merge sort
Merge sort is a divide-and-conquer sorting algorithm. It divides an array into halves until each subarray contains one value, then merges those subarrays back together in sorted order.
A one-element subarray is already sorted, so it is the base case. The algorithm proceeds as follows:
Divide the current range into a left half and a right half.
Recursively sort the left half.
Recursively sort the right half.
Merge the two sorted halves.
During a merge, the algorithm compares the first unprocessed value in each half and copies the smaller value into the output. It advances the pointer for the half from which that value came. When one half runs out of values, all remaining values from the other half are copied across; that half is already sorted.
A typical implementation keeps track of the current start, midpoint, and end of the range. It uses a temporary array for the merge, then copies the merged results into the corresponding range of the original array. The recursive calls operate on smaller index ranges, not on entirely separate problems.
Merge sort takes O(nlogn) time, since each level processes a total of n values and the array is divided for about logn levels. A standard array implementation uses O(n) auxiliary space for merging, in addition to the recursive call stack.
Recursion with linked lists
A linked list consists of nodes, each storing a value and a reference to the next node. Recursive algorithms can move through a list one node per call.
Reversing a linked list
To reverse a singly linked list recursively:
Base case: If the head is null or the head has no next node, return the head. An empty list and a one-node list are already reversed.
Recursive step: Reverse the list starting at the next node.
Unwinding step: When the recursive call returns, make the next node point back to the current node, then remove the current node’s old forward link.
Return value: Return the new head produced by the deepest call.
For a list 1→2→3, the recursive call reaches node 3, which becomes the new head. While the earlier calls return, the links are redirected so that 3→2→1. Removing each old forward link is essential; otherwise, the list could contain cycles.
The algorithm takes O(n) time and uses O(n) call-stack space for a list of n nodes.
Merging two sorted linked lists
Two sorted linked lists can be merged recursively by choosing the smaller head node at each step.
Base case: If one list is null, return the other list. If both are null, this naturally returns null.
Recursive case: Compare the two head values. The smaller node becomes the next node in the merged list. Recursively merge the remainder of that node’s list with the other list, and attach the result after the chosen node.
For example, if the current heads are 1 and 4, the node containing 1 is selected. The algorithm then compares the next node from the first list with the unchanged head of the second list. Each recursive result is assigned as the chosen node’s next reference.
The recursive calls select nodes in sorted order. When one list runs out, the other list is already sorted and can be attached as the remainder. The merge takes O(m+n) time for lists of lengths m and n, and the recursive implementation can use up to O(m+n) call-stack space.
Recursion with trees
A tree is a hierarchical structure made of nodes connected to child nodes. A binary tree has at most two children per node. Trees are naturally suited to recursion because a child and its descendants form a smaller tree of the same kind.
Inserting into a binary search tree
A binary search tree (BST) orders values so that, for each node, values in its left subtree are smaller and values in its right subtree are larger. This rule applies throughout the tree, not just to the immediate children.
To insert a value:
If the current node is null, create a node containing the value. This is the insertion position.
If the value is smaller than the current node’s value, recursively insert into the left subtree.
If the value is larger, recursively insert into the right subtree.
Return the current node so that the original root remains available as the tree’s root.
For example, inserting 108 into a tree rooted at 100 begins by moving right because 108>100. If the next node is 120, the search moves left because 108<120. It continues until it reaches a null child position, where the new node is attached.
The new node is always inserted at a leaf position. If the tree is balanced, insertion takes O(logn) time; if it is highly unbalanced, it can take O(n) time. The recursion depth has the same dependence on the tree’s height.
Printing leaf nodes
A leaf node has no children. To print all leaf nodes in left-to-right order:
Return immediately if the current node is null.
If both children are null, print the current node’s value.
Otherwise, recursively explore the left subtree and then the right subtree.
The order of the recursive calls matters. Exploring the left subtree first ensures that its leaves are processed before those in the right subtree. This is a depth-first traversal: it follows one branch as far as possible before returning to explore another.
The traversal visits each node once, taking O(n) time for a tree with n nodes. Its call-stack space is O(h), where h is the tree’s height.
Depth-first search in graphs
A graph can contain cycles and can have multiple paths to the same node. This differs from a tree, where each non-root node has only one path from the root. Therefore, a graph traversal generally needs a visited set to prevent revisiting nodes indefinitely.
In a recursive depth-first search (DFS):
Start at a node and check whether it is the target.
Record the node as visited.
Examine its neighbors one at a time.
For each unvisited neighbor, recursively search from that neighbor.
If any recursive search finds the target, return success.
If all reachable neighbors have been explored without finding it, return failure.
DFS follows one path deeply before returning to consider other neighbors. If a node has several neighbors, the algorithm completes the exploration from one neighbor before moving to the next. The order among neighbors depends on how the graph provides them.
The visited set is essential in graphs with cycles. Before exploring a neighbor, the algorithm checks whether that node has already been visited. If it has, the search skips it. This prevents infinite recursion along a cycle and avoids unnecessary repeated work.
For a graph represented with adjacency lists, a full DFS takes O(V+E) time, where V is the number of vertices and E is the number of edges, assuming each vertex and edge is processed a bounded number of times. The visited set requires O(V) space, and recursive DFS may also use up to O(V) stack space.
Optimizing recursion
Memoization and caching
Memoization stores the result of a subproblem so it can be reused if the same subproblem appears again. It is particularly useful when a recursive algorithm has overlapping subproblems, as in Fibonacci calculation.
A memoized recursive function follows this pattern:
Check whether the answer for the current input is already stored.
If it is, return the stored answer immediately.
Otherwise, calculate the answer recursively.
Store the answer before returning it.
For Fibonacci, the cache can store each value once. After F(3) has been calculated, later requests for F(3) can retrieve it rather than rebuilding its entire recursion tree. A hash map commonly provides average-case O(1) lookup and insertion.
With memoization, Fibonacci can be computed in O(n) time because each value from F(0) through F(n) is calculated once. The cache requires O(n) space, and the recursive call stack can use up to O(n) additional space.
Memoization reduces repeated computation; it does not necessarily eliminate recursion or its stack depth.
Tail-call optimization
A recursive call is in tail position when it is the final operation a function performs before returning. If a function must still do work after the recursive call returns, that call is not tail-recursive.
For example, a factorial definition that returns n×factorial(n−1) is not tail-recursive: multiplication remains after the recursive call. The function must preserve the current value of n until the recursive result returns.
An accumulator can sometimes reorganize the computation so that the recursive call is the final operation. In languages and implementations that support tail-call optimization, the compiler may reuse the current stack frame instead of adding a new one for each call. This can reduce stack growth and help prevent stack overflows.
Support is language- and implementation-dependent. Many functional languages support tail-call optimization, while commonly used languages such as Python and Java do not generally guarantee it. JavaScript support also depends on the environment. A programmer should not assume that a tail-recursive function will use constant stack space unless the language and runtime explicitly provide that behavior.
Key principles for designing recursive solutions
When approaching a problem recursively, a student can ask:
What is the smallest input that can be answered directly? This helps identify the base case.
What smaller version of the same problem remains? This defines the recursive call.
How does each call make progress toward the base case? The input or state must change in a meaningful way.
What work remains after the recursive call returns? This clarifies how results are combined or how pointers are updated.
Could the same subproblem be solved repeatedly? If so, memoization may help.
Could the recursion become too deep? If so, an iterative approach or a supported tail-call optimization may be preferable.
Recursion is most effective when the subproblems are well-defined, each call makes clear progress, and the base case captures a genuinely simple instance. Its call stack supplies a natural mechanism for remembering unfinished work, while each return carries results back toward the original problem.

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