Start from foundations · Course contents · فارسی
Previous lesson: Cost analysis from scratch: counting work and time growth · Next lesson: The Master method from scratch: levels, leaves and local work
In the previous lesson, we counted loop iterations. Sometimes we describe a problem using a smaller version of itself: to sum three elements, find the sum of the first two and add the third. Recursion means a function calls itself during execution. Rather than putting every repetition in one loop, we delegate part of the work to a smaller call.
The objective is to trace calls and returns, recognize a stopping condition, and construct costs for simple patterns. No programming language is assumed; functions are introduced below. Operation counting and Θ notation from the previous lesson are required. This introduces recurrences; the general Master theorem and amortized analysis remain future topics.
1. A function takes input and returns an answer
Think of a function as a named instruction sequence: it runs with specified input and returns output. A call requests execution with particular input. sumPrefix(A, 3) asks for the sum of the first three elements of list A. Indices start at zero, so the third element is A[2].
sumPrefix(A, n):
if n == 0:
return 0
previous = sumPrefix(A, n-1)
return previous + A[n-1]
The contract requires integer n with 0<=n<=length(A). length(A) is the element count. With n=0, no elements are selected and their sum is zero. return ends this call and sends the specified value back to its caller. We pass a reference to the same A, without copying the list. Access and addition have constant cost under our machine-number model.
Two ingredients matter. A base case answers without another recursive call. A recursive case reduces the problem and uses the smaller answer. Merely having a base condition is insufficient: legal inputs must reach it. Here nonnegative n decreases by one until zero. Passing n again instead of n-1 would never reach the base from positive input.
2. A complete trace: descending is different from returning
For A=[2,5,4] and n=3:
| Step | What happens? |
|---|---|
| 1 | Call 3 requests call 2 to obtain previous; addition with 4 waits. |
| 2 | Call 2 requests call 1; addition with 5 waits. |
| 3 | Call 1 requests call 0; addition with 2 waits. |
| 4 | Call 0 returns zero. |
| 5 | Call 1 returns 0+2=2. |
| 6 | Call 2 returns 2+5=7. |
| 7 | Call 3 returns 7+4=11. |
The diagram separates requests from results. Reaching zero does not erase unfinished work: suspended operations resume when their requested result arrives.
A runtime commonly records unfinished calls in a call stack, preserving inputs and the point at which to resume. The most recently requested call returns first. Under the conventional model without call-elimination optimizations, this example has n+1 active calls at its deepest point and uses Θ(n) auxiliary space, excluding the input list. These calls are unfinished work, not simultaneous CPU execution.
3. A function's answer is different from its cost
The output above is eleven, but the computation makes three additions and four calls. A recurrence expresses a problem's cost using costs at smaller sizes. Let T(n) be running time, b the constant base-case cost, and c the constant local work of a non-base call. A simplified model is:
T(0) = b
T(n) = T(n-1) + c for n >= 1
c covers this call's work, such as its test, call preparation and addition. The entire child's execution is in T(n-1) and is not counted again in c. Expand:
T(n) = T(n-2) + 2c
= T(n-3) + 3c
= T(0) + nc
= b + nc
Running time is Θ(n). Counting additions alone gives a different recurrence: Add(0)=0, Add(n)=Add(n-1)+1, with exact answer n. Actual cost models can have different b and c; we cannot label every program's exact time n+1 without justification. The University of Wisconsin recursion reading discusses constructing cost recurrences.
4. What if the size halves each time?
Suppose an algorithm solves only one half-sized subproblem and performs constant other work. For easy counting, let n be a power of two, at least one:
T(1) = b
T(n) = T(n/2) + c
For n=8, sizes are 8 → 4 → 2 → 1: three non-base calls and one base call. Thus T(8)=b+3c. In general, log₂(n) halvings reach one, giving Θ(log n) time and call depth. This depends on constant local work. If constructing the subproblem copies half the array, count that copy separately. Merely seeing n/2 does not establish logarithmic time.
5. One half-sized call versus two
Now assume two half-sized subproblems and linear work to divide or combine. For powers of two:
T(1) = b
T(n) = 2T(n/2) + cn
At the first level, work outside the children is cn. The next level contains two nodes of size n/2, totaling 2*c*(n/2)=cn local work. Four nodes of size n/4 again total cn. There are log₂(n) non-base levels and finally n leaves of size one, each costing b. In this model, T(n)=cn log₂(n)+bn, hence Θ(n log n) growth.
For n=4, root work is 4c, next-level work is 4c, and four leaves contribute 4b: total 8c+4b. This is a simple recursion tree: each node is a call and its children are its requests. Height alone does not determine total time; node counts and local work matter too. The Cornell recurrence and recursion-tree reading develops the broader approach.
6. Independent practice and test traps
All questions are original. Write the trace or recurrence before opening an answer.
1. For A=[3,1], what are the output, addition count and total call count of sumPrefix(A,2)?
Answer 1
Calls descend 2 → 1 → 0; results return as zero, three and four. The output is 4, there are 2 additions, and there are 3 calls including the initial and base calls. Keep these quantities separate.
2. Keep the base condition n==0, but recurse with n+1. What happens from n=2?
Answer 2
Sizes become 2, 3, 4 and so on, never reaching zero. A real execution may fail from resource limits; that is not correct base-case termination or answer computation. Both a smaller problem and a path to the base matter.
3. In the exact model T(0)=2, T(n)=T(n-1)+3, find T(4) and its growth class.
Answer 3
Add 3 four times to the base cost 2: the result is 14. The formula is 2+3n and growth is Θ(n). The exact number belongs to this specified model.
4. Original multiple choice: For powers of two, T(n)=2T(n/2)+n with T(1)=1 has which tight bound? A) Θ(log n); B) Θ(n); C) Θ(n log n); D) Θ(n²).
Test answer
C. Each non-base level contributes n and there are log₂(n) such levels. The n leaves add linear cost. At n=4, the exact cost is 12. Counting halving while ignoring the two children is the trap.
5. Transfer: Rewrite prefix summation using a loop and one running-total variable. How do time and auxiliary space change?
Answer 5
Under the same machine-number model there are n additions and Θ(n) time. A loop with a fixed number of variables uses Θ(1) auxiliary space, avoiding the chain of n calls. Recursion is not automatically faster or more memory-efficient.
7. Retrieve and continue
Without looking, explain why a base case is necessary but insufficient. Distinguish output, call count and maximum depth using fresh data. If returns are unclear, write pending additions beside each call. If cost is wrong, separate each node's local work from its children's work. Independently tracing a call chain and constructing a recurrence is a practical continuation criterion; try another example after a gap.
References and authorship
Pseudocode, data, diagrams and exercises were authored for this lesson. Sources checked on 2026-11-23: University of Wisconsin: Recursion, for base cases and cost modeling; Cornell CS3110: Recursion Trees, for level-by-level analysis. This is an original lesson, not a translation or republication of those readings.
Prerequisite: counting operations · Course contents · Start from foundations
Previous lesson: Cost analysis from scratch: counting work and time growth · Next lesson: The Master method from scratch: levels, leaves and local work