How to read this guide. Every idea starts with plain words and an everyday picture, then gets its proper name, then code. Look for these markers:
- Predict — guess the answer before you run the code. Being wrong is useful.
- Pause and try — put the guide down and do it yourself first.
- Bridge — a short paragraph that says why the next idea comes next.
- New — a concept added to make the material friendlier for beginners (it was not in the first version of the plan).
Every Go snippet in this guide is a complete program. Save it as
main.goand rungo run .(Go 1.22 or newer, because we use nothing newer than that). The output shown under each snippet was produced by really running it. Timings depend on your machine, so only compare ratios.
Goal: by the end, students can estimate how an algorithm's cost grows, trace a recursive function by hand, write a correct base case and recursive case, and implement and test merge sort.
The road map:
| Step | Question we answer | Big idea |
|---|---|---|
| A1 | Why does a correct program take minutes? | Repeated work; exponential growth |
| A1 fixes | How do we stop repeating work? | Memoization, then a loop |
| A2 | How do we talk about "slow" in a precise way? | Counting steps and Big O |
| B0 | What actually happens when a function calls itself? | The call stack |
| B1 | Can recursion make a program faster? | Halving the problem (Power) |
| B2 | When is recursion the wrong tool? | Reverse a string two ways |
| C | How do we use halving to sort a million numbers? | Divide and conquer: merge sort |
#Warm-up toolkit: five words you will meet right away
You do not need to master these now. Read them once; each one comes back with a picture where we use it.
| Word | Plain meaning | Tiny example |
|---|---|---|
| function call | Asking a named recipe to run once, with the inputs you hand it. | double(21) |
| map | A lookup table (like a phone book): give a key, get a value back. | ages["Sara"] |
| closure | A function that remembers variables from the place where it was written. | next := func() int { count++; return count } |
| recursion | A function whose recipe says "to do this, call myself on a smaller problem". | Fib(n) calls Fib(n-1) |
| benchmark | A test that measures time instead of correctness. | BenchmarkFibNaive30 |
Predict, then run. What do you think each Println below prints? Write your guesses down first.
package main
import "fmt"
// A function: a named recipe. Calling it runs the recipe once.
func double(x int) int {
return x * 2
}
func main() {
// function call: ask the recipe to run with the input 21
fmt.Println(double(21)) // 42
// map: a lookup table from keys to values (like a phone book)
ages := make(map[string]int)
ages["Sara"] = 30
v, ok := ages["Sara"] // ok tells us whether the key was found
fmt.Println(v, ok) // 30 true
v, ok = ages["Omar"]
fmt.Println(v, ok) // 0 false (not found: zero value and ok == false)
// closure: a function that remembers the variables around it
count := 0
next := func() int {
count++ // it can read AND change count from outside
return count
}
fmt.Println(next(), next(), next()) // 1 2 3
}Output
42
30 true
0 false
1 2 3The second value in v, ok := ages["Sara"] is a "was it found?" flag. A key that is missing gives the zero value (0) and ok == false. We will use exactly this pattern in memoization.
NewNew — what does
nmean? In this whole guide,nis the size of the input: the number we pass toFib(n), the exponent inPower(x, n), the number of characters in a string, the number of items in a slice. "How long does it take?" is almost always answered as "it depends onn". A function that takes 1 second forn = 10and 1 hour forn = 20is a very different animal from one that takes 1 second and then 2 seconds.
Bridge. We are going to meet the word "slow" in the very next problem. A correct program can still be unusable, and the reason is not a slow computer. It is how much work the idea does.
#Block A: Why is this slow?
Everyday picture. You need the phone number of "Omar" in a printed phone book. Plan 1: read every name from page 1 until you hit Omar. Plan 2: open in the middle, see if Omar comes before or after, and throw half the book away; repeat. With 1,000,000 names, Plan 1 may take a million looks, Plan 2 about 20. Both plans are correct. Only one of them stays usable as the book grows. Block A is about noticing that difference, measuring it, and fixing it.
#Problem A1: Fibonacci
Statement. The Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, ... where each number is the sum of the previous two. Write Fib(n int) int. Example: Fib(10) = 55.
Build the intuition first. Start with 0 and 1. To get the next number, add the last two:
position: 0 1 2 3 4 5 6 7 8 9 10
value: 0 1 1 2 3 5 8 13 21 34 55
↑ ↑
1 = 0+1 2 = 1+1 3 = 1+2 5 = 2+3 ...So Fib(6) = Fib(5) + Fib(4) = 5 + 3 = 8. Notice that the definition of Fib(6) uses Fib on smaller inputs. That is recursion: a function defined in terms of itself on smaller inputs. The only thing to be careful about is where it stops. Fib(0) and Fib(1) are given directly (0 and 1); we call these the base cases. We will study recursion properly in Block B. For now, just read it as "copy the definition into code".
Students try first (the direct translation of the definition):
func FibNaive(n int) int {
if n < 2 {
return n
}
return FibNaive(n-1) + FibNaive(n-2)
}It is correct. Line by line: if n < 2 { return n } is the base case (Fib(0)=0, Fib(1)=1). The last line is the definition, word for word. "Naive" means "the obvious first attempt".
Predict. FibNaive(4) calls FibNaive(3) and FibNaive(2). How many calls happen in total, counting the first one? Guess before reading on.
See it happen. The snippet below prints one line per call. The indentation shows how many calls are "waiting" above it (the depth).
package main
import (
"fmt"
"strings"
)
// depth says how many calls are waiting above us; we indent by it.
func fibTrace(n, depth int) int {
indent := strings.Repeat(" ", depth)
fmt.Printf("%sfib(%d)\n", indent, n)
if n < 2 {
return n
}
return fibTrace(n-1, depth+1) + fibTrace(n-2, depth+1)
}
func main() {
fmt.Println("result:", fibTrace(4, 0))
}Output
fib(4)
fib(3)
fib(2)
fib(1)
fib(0)
fib(1)
fib(2)
fib(1)
fib(0)
result: 3That is 9 calls to compute a number that is just 3. Look at the output: fib(2) appears twice, and fib(1) three times. Keep that in mind.
NewNew — tracing recursion depth with indentation. Printing
strings.Repeat(" ", depth)before each message is the simplest debugging tool for recursion. You pass an extra parameterdepth, add 1 when you call yourself, and the output draws the call tree for you. We will reuse this trick forFactorialandPower.
Now ask them to run it for n = 30, n = 40, then n = 45.
Predict first. FibNaive(30) takes milliseconds. Will FibNaive(40) take about 10 times longer, 100 times longer, or 1000 times longer? And FibNaive(45)?
The wall. FibNaive(30) takes milliseconds, FibNaive(40) takes about a second, and FibNaive(45) takes several seconds (often 5–15, depending on the machine). FibNaive(50) would take minutes.
To measure time ourselves we record the clock before (time.Now()), run the function, and ask how much time passed (time.Since(start)):
package main
import (
"fmt"
"time"
)
func FibNaive(n int) int {
if n < 2 {
return n
}
return FibNaive(n-1) + FibNaive(n-2)
}
func main() {
for _, n := range []int{30, 35, 40} {
start := time.Now()
result := FibNaive(n)
elapsed := time.Since(start)
fmt.Printf("FibNaive(%d) = %d took %v\n", n, result, elapsed)
}
}Output
FibNaive(30) = 832040 took 3.46052ms
FibNaive(35) = 9227465 took 38.646644ms
FibNaive(40) = 102334155 took 439.15086msYour numbers will differ. On the machine used to check this guide, FibNaive(40) took 0.42 seconds and FibNaive(45) took about 4.9 seconds. On a slower laptop you will see the "about a second" and "5–15 seconds" from the plan. What matters is the pattern: every +5 on n multiplied the time by about 11 (3.5 ms → 38 ms → 420 ms). The time is not growing like a line; it is growing like a snowball.
Pause and try. Run the snippet with n = 41, 42, 43. Does each step cost about 1.6 times the previous one? (Hint: that number is about to show up again.)
Bridge. Why would adding just 5 to n make it 11 times slower? A computer does not get tired. So the program must be doing far more work than we think. The next step is to stop guessing and count the work.
Why: count the calls. Let students draw the call tree for FibNaive(5). (A call tree has one box for every call; a call's children are the calls it makes.)
fib(5)
├─ fib(4)
│ ├─ fib(3)
│ │ ├─ fib(2)
│ │ │ ├─ fib(1)
│ │ │ └─ fib(0)
│ │ └─ fib(1)
│ └─ fib(2)
│ ├─ fib(1)
│ └─ fib(0)
└─ fib(3)
├─ fib(2)
│ ├─ fib(1)
│ └─ fib(0)
└─ fib(1)Here is the same tree, reading from top to bottom and left to right (the order the computer works in). Only the first time a value is computed does the call do anything new. Everything marked REPEAT is work the computer has already done once and does again from scratch:
fib(5) new
├─ fib(4) new
│ ├─ fib(3) new
│ │ ├─ fib(2) new
│ │ │ ├─ fib(1) new
│ │ │ └─ fib(0) new
│ │ └─ fib(1) REPEAT
│ └─ fib(2) REPEAT (whole subtree below is wasted)
│ ├─ fib(1) REPEAT
│ └─ fib(0) REPEAT
└─ fib(3) REPEAT (whole subtree below is wasted)
├─ fib(2) REPEAT
│ ├─ fib(1) REPEAT
│ └─ fib(0) REPEAT
└─ fib(1) REPEATOut of 15 calls, only 6 are new. 9 are repeats. The same picture as a diagram (repeats are red):
fib(3) is computed twice, fib(2) three times, and the same work is repeated over and over.
Everyday picture. Imagine you ask a friend for Fib(5). She asks two other friends for Fib(4) and Fib(3). Those friends do not talk to each other, so both of them ask other friends for Fib(2), and so on. Hundreds of people end up answering the same question.
Instead of drawing bigger trees, let the computer count. We add a global counter (a variable outside the function) that goes up by one each time the function is called:
package main
import "fmt"
var calls int // a global counter: every call adds one
func FibNaive(n int) int {
calls++
if n < 2 {
return n
}
return FibNaive(n-1) + FibNaive(n-2)
}
func main() {
for _, n := range []int{5, 10, 20, 30} {
calls = 0 // reset before each run
result := FibNaive(n)
fmt.Printf("n=%2d Fib(n)=%7d calls=%9d\n", n, result, calls)
}
}Output
n= 5 Fib(n)= 5 calls= 15
n=10 Fib(n)= 55 calls= 177
n=20 Fib(n)= 6765 calls= 21891
n=30 Fib(n)= 832040 calls= 2692537The total number of calls for n is 2*Fib(n+1) - 1. We do not have to run the slow function to know this. The loop version from the next section computes Fib(n+1) instantly, so we can predict the calls even for n = 45 and n = 50:
package main
import "fmt"
func FibIter(n int) int {
a, b := 0, 1
for i := 0; i < n; i++ {
a, b = b, a+b
}
return a
}
// calls(n) = 2*Fib(n+1) - 1, so we never need to RUN the slow function.
func callsNeeded(n int) int {
return 2*FibIter(n+1) - 1
}
func main() {
for _, n := range []int{5, 10, 30, 44, 45, 50} {
c := callsNeeded(n)
fmt.Printf("n=%2d calls=%14d\n", n, c)
}
// growth factor from one n to the next
fmt.Printf("callsNeeded(45)/callsNeeded(44) = %.4f\n", float64(callsNeeded(45))/float64(callsNeeded(44)))
}Output
n= 5 calls= 15
n=10 calls= 177
n=30 calls= 2692537
n=44 calls= 2269806339
n=45 calls= 3672623805
n=50 calls= 40730022147
callsNeeded(45)/callsNeeded(44) = 1.6180| n | calls |
|---|---|
| 5 | 15 |
| 10 | 177 |
| 30 | 2,692,537 |
| 45 | 3,672,623,805 |
| 50 | 40,730,022,147 |
The number of calls multiplies by about 1.6 each time n grows by one. That is exponential growth, written O(2^n) as a simple upper bound.
NewNew — why 1.6? The bigger the
Fibnumbers get, the closer the ratio of one to the next gets to 1.618..., the "golden ratio". The calls followFib, so they grow by that same factor per step. (That is why the printed ratio above is1.6180.) "2^n" is a simpler, slightly generous way of saying "multiplies by a constant bigger than 1 every timengoes up by 1".
What "exponential" feels like. Fold a sheet of paper in half 42 times and it reaches the moon. Each fold doubles the thickness. Exponential growth is slow at the start and then suddenly impossible. That is why n = 30 feels fine and n = 50 feels hopeless.
Bridge. The tree shows the disease: we solve the same small questions again and again. The cure is just as simple as the disease. Write each answer down the first time and look it up afterwards.
The fix, step 1: memoization. Remember each answer the first time it is computed.
Everyday picture. A student keeps a notebook. Before working out Fib(3), she checks the notebook: "Did I already do this?" If yes, she copies the answer. If not, she works it out and writes it in. The notebook is the map from the warm-up: key = k, value = Fib(k). ("Memoization" is spelled like "memo", a note to self, not "memorization".)
func FibMemo(n int) int {
memo := make(map[int]int)
var fib func(int) int
fib = func(k int) int {
if k < 2 {
return k
}
if v, ok := memo[k]; ok {
return v
}
memo[k] = fib(k-1) + fib(k-2)
return memo[k]
}
return fib(n)
}How to read it, one piece at a time:
memo := make(map[int]int)creates the notebook (empty).fibis a closure: a function written insideFibMemothat can see and changememo. The notebook is shared by all the calls and disappears whenFibMemoreturns.if k < 2 { return k }is the base case again.if v, ok := memo[k]; ok { return v }is "check the notebook first".memo[k] = fib(k-1) + fib(k-2)is "work it out, and write it down".
A recursive closure must be declared first (var fib func(int) int) and assigned after, because the function body refers to fib itself. (Go reads fib = func ... fib(k-1) ... and would complain that fib does not exist yet if we used fib := func ....)
Watch the notebook fill. This snippet prints every notebook decision for Fib(6):
package main
import (
"fmt"
"sort"
)
func main() {
memo := make(map[int]int)
calls := 0
var fib func(int) int
fib = func(k int) int {
calls++
if k < 2 {
return k
}
if v, ok := memo[k]; ok {
fmt.Printf(" fib(%d): already in memo -> %d (reuse!)\n", k, v)
return v
}
memo[k] = fib(k-1) + fib(k-2)
fmt.Printf(" fib(%d): computed and saved memo[%d] = %d\n", k, k, memo[k])
return memo[k]
}
fmt.Println("result:", fib(6))
fmt.Println("calls:", calls)
keys := make([]int, 0, len(memo))
for k := range memo {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
fmt.Printf("memo[%d] = %d\n", k, memo[k])
}
}Output
fib(2): computed and saved memo[2] = 1
fib(3): computed and saved memo[3] = 2
fib(2): already in memo -> 1 (reuse!)
fib(4): computed and saved memo[4] = 3
fib(3): already in memo -> 2 (reuse!)
fib(5): computed and saved memo[5] = 5
fib(4): already in memo -> 3 (reuse!)
fib(6): computed and saved memo[6] = 8
result: 8
calls: 11
memo[2] = 1
memo[3] = 2
memo[4] = 3
memo[5] = 5
memo[6] = 8The same story as a table. Read the rows top to bottom:
| Step | Call | Notebook before | What happens | Notebook after |
|---|---|---|---|---|
| 1 | fib(6) → fib(5) → fib(4) → fib(3) → fib(2) | empty | fib(1) and fib(0) are base cases, so memo[2] = 1 | {2:1} |
| 2 | back in fib(3), ask fib(1) | {2:1} | base case, so memo[3] = 2 | {2:1, 3:2} |
| 3 | back in fib(4), ask fib(2) | {2:1, 3:2} | hit: reuse 1, so memo[4] = 3 | {2:1, 3:2, 4:3} |
| 4 | back in fib(5), ask fib(3) | {..., 4:3} | hit: reuse 2, so memo[5] = 5 | {2:1, ..., 5:5} |
| 5 | back in fib(6), ask fib(4) | {..., 5:5} | hit: reuse 3, so memo[6] = 8 | {2:1, 3:2, 4:3, 5:5, 6:8} |
Now the call tree for FibMemo(5) has no wasted subtrees. Orange boxes are notebook hits; they return at once and do not call anything:
9 calls instead of 15 for n = 5. For n = 6 the program printed calls: 11. In general it is 2n - 1 calls. Now each value is computed once, so the work is about 2n calls: O(n) time and O(n) space for the map and the call stack.
NewNew — top-down versus bottom-up (dynamic programming).
FibMemois top-down: start from the big questionfib(n)and let the recursion discover which smaller answers are needed (and remember them). The opposite, bottom-up, starts from the smallest answers and builds upward in a loop, so no recursion is needed. Both are called dynamic programming: "solve each small problem once, store it, reuse it". The next fix is the bottom-up version.
Bridge. The notebook shows something important: to compute fib(k) we only ever look at fib(k-1) and fib(k-2). Everything older is never used again. So why keep the whole notebook?
The fix, step 2: a loop. Since only the last two values matter, keep just those:
func FibIter(n int) int {
a, b := 0, 1
for i := 0; i < n; i++ {
a, b = b, a+b
}
return a
}("Iter" is short for iterative, meaning "uses a loop".) Read a, b = b, a+b as: "the new a is the old b; the new b is the old a plus the old b." Go evaluates the whole right side first, so the two assignments do not step on each other. Think of a and b as two fingers on the sequence, sliding one step to the right each turn.
O(n) time and O(1) space. Trace for n = 5: (a,b) goes (0,1) → (1,1) → (1,2) → (2,3) → (3,5) → (5,8), and the loop returns a = 5.
package main
import "fmt"
func main() {
n := 5
a, b := 0, 1
fmt.Printf("start (a,b) = (%d,%d)\n", a, b)
for i := 0; i < n; i++ {
a, b = b, a+b
fmt.Printf("after i=%d (a,b) = (%d,%d)\n", i, a, b)
}
fmt.Println("return a =", a)
}Output
start (a,b) = (0,1)
after i=0 (a,b) = (1,1)
after i=1 (a,b) = (1,2)
after i=2 (a,b) = (2,3)
after i=3 (a,b) = (3,5)
after i=4 (a,b) = (5,8)
return a = 5As a state table (the two fingers moving along the sequence 0 1 1 2 3 5 8):
| After step | a (finger 1) | b (finger 2) | Picture |
|---|---|---|---|
| start | 0 | 1 | [0] [1] 1 2 3 5 8 |
| i = 0 | 1 | 1 | 0 [1] [1] 2 3 5 8 |
| i = 1 | 1 | 2 | 0 1 [1] [2] 3 5 8 |
| i = 2 | 2 | 3 | 0 1 1 [2] [3] 5 8 |
| i = 3 | 3 | 5 | 0 1 1 2 [3] [5] 8 |
| i = 4 | 5 | 8 | 0 1 1 2 3 [5] [8] |
After n steps, a sits on Fib(n). That is why we return a.
NewNew — the loop is the notebook, squeezed. Here is the same bottom-up idea with a full table (a slice) instead of two variables. It makes the link between the notebook and the loop visible:
package main import "fmt" // Bottom-up with a table: start from the smallest answers and build upward. func FibTable(n int) int { if n < 2 { return n } table := make([]int, n+1) table[0], table[1] = 0, 1 for k := 2; k <= n; k++ { table[k] = table[k-1] + table[k-2] fmt.Printf("table[%d] = table[%d] + table[%d] = %d\n", k, k-1, k-2, table[k]) } return table[n] } func main() { fmt.Println("FibTable(6) =", FibTable(6)) }Output
table[2] = table[1] + table[0] = 1 table[3] = table[2] + table[1] = 2 table[4] = table[3] + table[2] = 3 table[5] = table[4] + table[3] = 5 table[6] = table[5] + table[4] = 8 FibTable(6) = 8The table needs
n+1slots (O(n) space). Buttable[k]only ever reads the previous two slots, so two variables are enough: that isFibIter, with O(1) space.
Overflow note. Fib(92) is 7,540,113,804,746,346,429, the largest Fibonacci number that fits in a 64-bit int. Fib(93) silently wraps around to a wrong (negative) value. Ask students how they could detect it (compare before adding, as in the week 1 reverse-number homework) or avoid it (math/big).
Everyday picture. A car's odometer with 5 digits goes from 99999 to 00000. It does not complain; it just wraps. A 64-bit int does the same with a limit of 9,223,372,036,854,775,807 (math.MaxInt), except that the wrap lands on a negative number.
Predict. Which of the three lines below will print a negative number?
package main
import (
"errors"
"fmt"
"math"
"math/big"
)
func FibIter(n int) int {
a, b := 0, 1
for i := 0; i < n; i++ {
a, b = b, a+b
}
return a
}
// Detect the problem BEFORE adding: a+b fits only if a <= MaxInt - b.
func FibChecked(n int) (int, error) {
a, b := 0, 1
for i := 0; i < n; i++ {
if a > math.MaxInt-b {
return 0, errors.New("overflow: result does not fit in int")
}
a, b = b, a+b
}
return a, nil
}
// Avoid the problem: big.Int grows as large as needed.
func FibBig(n int) *big.Int {
a, b := big.NewInt(0), big.NewInt(1)
for i := 0; i < n; i++ {
a, b = b, new(big.Int).Add(a, b)
}
return a
}
func main() {
fmt.Println("largest int:", math.MaxInt)
fmt.Println("Fib(92) =", FibIter(92))
fmt.Println("Fib(93) =", FibIter(93), "<- wrapped around, wrong!")
fmt.Println(FibChecked(92))
fmt.Println(FibChecked(93))
fmt.Println("Fib(93) with big =", FibBig(93))
}Output
largest int: 9223372036854775807
Fib(92) = 7540113804746346429
Fib(93) = -6246583658587674878 <- wrapped around, wrong!
0 overflow: result does not fit in int
0 overflow: result does not fit in int
Fib(93) with big = 12200160415121876738The "detect" trick is in FibChecked: before adding, ask whether a + b would be too big by asking the safe question a > math.MaxInt - b (subtraction cannot overflow here). The "avoid" trick is math/big, whose numbers grow to any size, at the cost of speed. Note that Fib(93) = 12,200,160,415,121,876,738 is a perfectly good number; it just does not fit in an int.
Measure it with a benchmark. A benchmark is a test function that measures speed. In Go it lives in a _test.go file, starts with Benchmark, takes a *testing.B, and runs the code b.N times. Go chooses b.N itself (it keeps raising it until the timing is stable), so you never pick it.
func BenchmarkFibNaive30(b *testing.B) {
for i := 0; i < b.N; i++ {
FibNaive(30)
}
}
func BenchmarkFibMemo30(b *testing.B) {
for i := 0; i < b.N; i++ {
FibMemo(30)
}
}
func BenchmarkFibIter30(b *testing.B) {
for i := 0; i < b.N; i++ {
FibIter(30)
}
}Run go test -bench=. -benchmem. Expect the naive version in the milliseconds (millions of calls) and the other two in nanoseconds to microseconds, a gap of several orders of magnitude. The exact numbers depend on the machine, so focus on the ratio. -benchmem also shows allocations: the memo version allocates a map, the loop allocates nothing.
NewNew — how to read benchmark output. Here is real output (from
go test -bench=. -benchmem -run='^$';-run='^$'skips the ordinary tests so only benchmarks run):Output
goos: linux goarch: amd64 pkg: week4/week4 cpu: Intel(R) Xeon(R) Processor BenchmarkFibNaive30-8 324 3630365 ns/op 0 B/op 0 allocs/op BenchmarkFibMemo30-8 563071 1990 ns/op 2120 B/op 7 allocs/op BenchmarkFibIter30-8 120748383 9.870 ns/op 0 B/op 0 allocs/op PASS ok week4/week4 4.874sReading one line,
BenchmarkFibMemo30-8 563071 1990 ns/op 2120 B/op 7 allocs/op:
Piece Meaning BenchmarkFibMemo30-8name of the benchmark; -8is how many CPU threads Go may use563071b.N: how many times Go ran the function to get a stable timing1990 ns/opaverage time for one call, in nanoseconds (1 ns = one billionth of a second) 2120 B/opbytes of memory allocated per call ( -benchmem)7 allocs/ophow many separate memory allocations per call ( -benchmem)Ratios here:
FibNaive(30)took 3,630,365 ns (about 3.6 ms),FibMemo(30)about 1,990 ns,FibIter(30)about 9.9 ns. So the loop is roughly 370,000 times faster than the naive version, and the memo version roughly 1,800 times faster. Lowerns/opis better;0 allocs/opmeans the loop never asked for extra memory.
Tests (all three must agree): 0 → 0, 1 → 1, 2 → 1, 10 → 55, 20 → 6765, 30 → 832040, 50 → 12586269025, 92 → 7540113804746346429. (Run the naive version only on the small values: it would take minutes for 50 and years for 92.)
Summary of A1.
| Version | Idea | Time | Extra space | Fib(30) benchmark |
|---|---|---|---|---|
FibNaive | copy the definition | O(2^n) | O(n) call stack | about 3.6 ms |
FibMemo | recursion + notebook (top-down) | O(n) | O(n) map and call stack | about 2 µs |
FibIter | loop with two variables (bottom-up) | O(n) | O(1) | about 10 ns |
Bridge. We have used words like "O(2^n)" and "O(n)" for a while. It is time to say precisely what they mean and how to work them out without running anything.
#Counting operations and Big O
The idea. Big O describes how the number of steps grows as the input size n grows, ignoring machine speed and small details.
Everyday picture. Moving house. If you have n boxes and carry each one once, the job grows in proportion to n. It does not matter if your friend carries twice as fast: double the boxes still means double the work. Big O is the "double the boxes, what happens to the work?" question. If the answer is "double", the cost is O(n). If it is "four times", it is O(n²). If it is "just one more trip", it is O(log n).
Four simplification rules:
- Drop constants: 3n and n/2 are both O(n).
- Drop lower-order terms: n² + n is O(n²).
- Sequential loops add: two separate loops over n are O(n + n) = O(n).
- Nested loops multiply: a loop of n inside a loop of n is O(n²).
Why these rules are fair. For n = 1,000, n² + n is 1,001,000: the + n is 0.1% of the total and shrinks to nothing as n grows (rule 2). Constants like the 3 in 3n depend on the computer and the compiler, and the question is about the shape of growth, so we ignore them (rule 1).
NewNew — best, worst and average case. The same function can take different numbers of steps for different inputs of the same size. Searching a slice from the left shows it:
package main import "fmt" // returns the index of target (or -1) and how many items it looked at func linearSearch(items []int, target int) (int, int) { looked := 0 for i, v := range items { looked++ if v == target { return i, looked } } return -1, looked } func main() { items := []int{7, 3, 9, 1, 5, 8, 2, 6, 4, 10} for _, target := range []int{7, 5, 10, 99} { idx, looked := linearSearch(items, target) fmt.Printf("target=%-3d index=%-3d looked at %d of %d items\n", target, idx, looked, len(items)) } }Output
target=7 index=0 looked at 1 of 10 items target=5 index=4 looked at 5 of 10 items target=10 index=9 looked at 10 of 10 items target=99 index=-1 looked at 10 of 10 items
- Best case: the target is first, so 1 step.
- Worst case: the target is last or missing, so
nsteps.- Average case: about
n/2steps if the target is equally likely to be anywhere.Unless someone says otherwise, "Big O" means the worst case: a promise that it will never be slower than this. All the classifications in this guide are worst case, and the constant
1/2in the average case disappears by rule 1 anyway.
Common growth rates, from fast to slow:
| Notation | Name | Example |
|---|---|---|
| O(1) | constant | index into a slice, push onto a stack |
| O(log n) | logarithmic | binary search, halving a problem each step |
| O(n) | linear | one loop over the input, a linear search |
| O(n log n) | linearithmic | merge sort, sort.Slice |
| O(n²) | quadratic | nested loops, bubble sort |
| O(2^n) | exponential | naive Fibonacci, trying every subset |
NewNew — what "log n" really means: halving.
log₂(n)answers "how many times can I cutnin half before I reach 1?" Cut 8 → 4 → 2 → 1: three cuts, solog₂(8) = 3. That is why binary search (throw half the phone book away each time) andPower(halve the exponent each time) are O(log n). You do not need a calculator for the intuition: every time the input doubles, an O(log n) algorithm needs only one more step.package main import ( "fmt" "math" ) func main() { // how many times can we halve n until we reach 1? for _, n := range []int{8, 10, 100, 1000, 1000000, 1000000000} { steps, v := 0, n for v > 1 { v /= 2 steps++ } fmt.Printf("n=%-11d halvings=%-3d log2(n)=%.2f\n", n, steps, math.Log2(float64(n))) } }Output
n=8 halvings=3 log2(n)=3.00 n=10 halvings=3 log2(n)=3.32 n=100 halvings=6 log2(n)=6.64 n=1000 halvings=9 log2(n)=9.97 n=1000000 halvings=19 log2(n)=19.93 n=1000000000 halvings=29 log2(n)=29.90Even for a billion, only 29 or 30 halvings. (We use integer division, which drops remainders. That is why the loop counts 29 for 1,000,000,000 while
log₂is 29.90.) A billion items, about 30 steps: that is why O(log n) feels like magic.
Growth side by side. The same table made visible. For n = 16, one block █ stands for 4 steps:
O(1) █ 1
O(log n) █ 4
O(n) ████ 16
O(n log n) ████████████████ 64
O(n²) ████████████████████████████████████████████████████████████████ 256
O(2^n) (16,384 blocks: it does not fit on any screen) 65,536And as a chart for n = 1 to 10 (the 2^n line shoots up while the others barely move):
(Lines from the bottom: n, n log₂ n, n², 2^n. If your Markdown viewer does not draw Mermaid, use the table below instead.)
To feel the difference, for n = 1,000,000: O(n) is a million steps, O(n log n) is about 20 million, O(n²) is a trillion, and O(2^n) is a number with 300,000 digits (to be exact, 301,030 digits). The program below prints these (and more) so you can check them:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Printf("%-10s %-12s %-14s %-18s %s\n", "n", "log2(n)", "n*log2(n)", "n*n", "2^n")
for _, n := range []int{10, 20, 50, 100, 1000, 1000000} {
f := float64(n)
var exp string
if n <= 50 {
exp = fmt.Sprintf("%.0f", math.Pow(2, f))
} else {
digits := int(math.Floor(f*math.Log10(2))) + 1
exp = fmt.Sprintf("a number with %d digits", digits)
}
fmt.Printf("%-10d %-12.1f %-14.0f %-18.0f %s\n", n, math.Log2(f), f*math.Log2(f), f*f, exp)
}
}Output
n log2(n) n*log2(n) n*n 2^n
10 3.3 33 100 1024
20 4.3 86 400 1048576
50 5.6 282 2500 1125899906842624
100 6.6 664 10000 a number with 31 digits
1000 10.0 9966 1000000 a number with 302 digits
1000000 19.9 19931569 1000000000000 a number with 301030 digitsPause and try. At 1 billion simple steps per second, how long does the n = 1,000,000 case take for O(n)? For O(n²)? (Answers: O(n) is 10⁶ steps ÷ 10⁹ per second = 1 millisecond. O(n²) is 10¹² steps ÷ 10⁹ per second = 1,000 seconds, about 17 minutes. O(2^n) will never finish.)
Classify these (answers included). Try each one yourself first. Cover the answers.
for i := range n { for j := range n { work() } }→ O(n²).for i := 1; i < n; i *= 2 { work() }→ O(log n), because i doubles each time.- One loop to n, then another loop to n → O(n) (rule 3).
for i := range n { for j := i; j < n; j++ { work() } }→ O(n²): about n²/2 steps, and the constant is dropped.- A function that does O(1) work and then calls itself on half the input → O(log n).
- A function that calls itself twice on n-1 → O(2^n).
(for i := range n loops i from 0 to n-1; it needs Go 1.22 or newer.)
Check your answers by counting. Each function below calls work(), which adds 1 to a counter. Watch how the count changes when n doubles:
package main
import "fmt"
var steps int
func work() { steps++ }
func nested(n int) { // 1. O(n^2)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
work()
}
}
}
func doubling(n int) { // 2. O(log n)
for i := 1; i < n; i *= 2 {
work()
}
}
func twoLoops(n int) { // 3. O(n)
for i := 0; i < n; i++ {
work()
}
for i := 0; i < n; i++ {
work()
}
}
func triangle(n int) { // 4. O(n^2): about n*n/2 steps
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
work()
}
}
}
func halving(n int) { // 5. O(log n)
if n <= 1 {
return
}
work()
halving(n / 2)
}
func twice(n int) { // 6. O(2^n)
if n <= 0 {
return
}
work()
twice(n - 1)
twice(n - 1)
}
func count(f func(int), n int) int {
steps = 0
f(n)
return steps
}
func main() {
fmt.Printf("%-3s %-10s %8s %8s %8s %8s\n", "#", "name", "n=8", "n=16", "n=32", "n=64")
rows := []struct {
name string
f func(int)
}{{"nested", nested}, {"doubling", doubling}, {"twoLoops", twoLoops}, {"triangle", triangle}, {"halving", halving}}
for i, r := range rows {
fmt.Printf("%-3d %-10s %8d %8d %8d %8d\n", i+1, r.name, count(r.f, 8), count(r.f, 16), count(r.f, 32), count(r.f, 64))
}
// twice() explodes, so use smaller n
fmt.Printf("%-3d %-10s n=5:%d n=10:%d n=15:%d n=20:%d\n", 6, "twice",
count(twice, 5), count(twice, 10), count(twice, 15), count(twice, 20))
}Output
# name n=8 n=16 n=32 n=64
1 nested 64 256 1024 4096
2 doubling 3 4 5 6
3 twoLoops 16 32 64 128
4 triangle 36 136 528 2080
5 halving 3 4 5 6
6 twice n=5:31 n=10:1023 n=15:32767 n=20:1048575How to read the table: when n doubles (8 → 16 → 32 → 64), a quadratic count (rows 1 and 4) multiplies by about 4; a linear count (row 3) doubles; a logarithmic count (rows 2 and 5) goes up by just 1. Row 6 is the explosion: each +5 on n multiplies the count by about 32 (31 → 1,023 → 32,767 → 1,048,575, which is 2^(n+1) - 1).
Space matters too. Memoization trades memory for time: FibMemo uses O(n) extra space to save exponential time. Always ask about both.
Bridge to Block B. All the recursive functions so far were taken on trust: we wrote FibNaive and it "just worked". Row 5 and row 6 above were also recursive. To predict their cost, and to write our own, we need to see exactly what the computer does when a function calls itself.
#Block B: Recursive thinking
Everyday picture. You are in a long queue and want to know your position. You cannot see the front. So you tap the person ahead and ask "what is your position?" She does not know either, so she taps the person ahead of her, and so on, until someone at the very front says "I am number 1". Then the answers travel back: "2", "3", "4"... until it reaches you. Notice the three things that make this work:
- Everyone asks the same question of someone closer to the front (smaller problem).
- Someone at the front can answer without asking (the base case).
- Each person waits with their own little bit of information until the answer comes back (that waiting room is the call stack).
Words, before code.
- A function call is one run of a function with particular inputs.
- A stack frame (or just frame) is the notebook page the computer makes for one call: it holds that call's parameters, its local variables, and a note about where to return to when it finishes.
- The call stack is the pile of frames for all calls that have started and not yet finished. Like a stack of plates you only add to the top (push) and take from the top (pop).
- A recursive function is a function that calls itself.
- The base case is the input for which the function answers directly, without calling itself. The recursive case is the part that calls itself on a smaller problem.
Warm-up: the call stack. Every function call gets its own frame holding its parameters and local variables. When a function calls itself, a new frame is pushed; when it returns, the frame is popped. Trace this by hand:
func Factorial(n int) int {
if n <= 1 {
return 1
}
return n * Factorial(n-1)
}(Factorial(4) means 4 × 3 × 2 × 1 = 24. Note how it is defined by itself: Factorial(4) = 4 * Factorial(3).)
Predict. Before reading the trace: how many frames exist on the stack at the deepest moment of Factorial(4)?
Factorial(4) goes down: 4 * Factorial(3), then 3 * Factorial(2), then 2 * Factorial(1), then Factorial(1) returns 1 (the base case). The stack then unwinds: 2*1 = 2, 3*2 = 6, 4*6 = 24. Every recursive function needs (1) a base case that stops the recursion, and (2) a recursive case that moves toward it.
Here is the same trace printed by the computer. PUSH happens when a call starts, POP when it returns. This is the depth-indentation trick from Block A:
package main
import (
"fmt"
"strings"
)
func Factorial(n, depth int) int {
pad := strings.Repeat(" ", depth)
fmt.Printf("%sPUSH Factorial(%d)\n", pad, n)
if n <= 1 {
fmt.Printf("%sPOP Factorial(%d) returns 1 <- base case\n", pad, n)
return 1
}
result := n * Factorial(n-1, depth+1)
fmt.Printf("%sPOP Factorial(%d) returns %d\n", pad, n, result)
return result
}
func main() {
fmt.Println("answer:", Factorial(4, 0))
}Output
PUSH Factorial(4)
PUSH Factorial(3)
PUSH Factorial(2)
PUSH Factorial(1)
POP Factorial(1) returns 1 <- base case
POP Factorial(2) returns 2
POP Factorial(3) returns 6
POP Factorial(4) returns 24
answer: 24And here is the stack itself, one snapshot per step (in each column the top of the stack is the top box). The answer to the prediction: four frames at the deepest moment (snapshot 4).
1. call F(4) 2. call F(3) 3. call F(2) 4. call F(1)
┌──────────────────┐
┌──────────────────┐ │ F(1) n=1 base │
┌──────────────────┐ │ F(2) n=2 │ ├──────────────────┤
┌──────────────────┐ │ F(3) n=3 │ ├──────────────────┤ │ F(2) n=2 │
│ F(4) n=4 │ ├──────────────────┤ │ F(3) n=3 │ ├──────────────────┤
└──────────────────┘ │ F(4) n=4 │ ├──────────────────┤ │ F(3) n=3 │
└──────────────────┘ │ F(4) n=4 │ ├──────────────────┤
└──────────────────┘ │ F(4) n=4 │
└──────────────────┘
5. F(1) gives 1 6. F(2) gives 2 7. F(3) gives 6 8. F(4) gives 24
┌──────────────────┐
│ F(2) 2*1 = 2 │ ┌──────────────────┐
├──────────────────┤ │ F(3) 3*2 = 6 │ ┌──────────────────┐
│ F(3) n=3 │ ├──────────────────┤ │ F(4) 4*6 = 24 │
├──────────────────┤ │ F(4) n=4 │ └──────────────────┘ (empty stack)
│ F(4) n=4 │ └──────────────────┘
└──────────────────┘Three things to notice: the stack grows down the recursion (steps 1 to 4) and shrinks on the way back (steps 5 to 8); each frame has its own copy of n, so F(3) still has n=3 while F(1) runs; and no multiplication is done on the way down. All the multiplying happens on the way back, as frames pop.
Pause and try. Draw the stack for Factorial(3) on paper, then check against the printed trace by changing 4 to 3 in the snippet. Then try Factorial(0) and Factorial(1). Why do both give 1?
NewNew — where do frames live? The stack versus the heap, in Go. Go gives the computer's memory two main working areas. The stack holds the frames of running function calls. It is fast, and it is cleaned up automatically as each call returns (a pop). The heap holds values that must outlive the call that made them or whose size is not known in advance (for example a
map, or the storage behind a growing slice). The heap is cleaned by the garbage collector some time after nothing uses the data any more.In Go you do not choose. The compiler decides, using escape analysis: if a value can still be reached after its function returns, it "escapes" to the heap. You can ask the compiler what it decided with
go build -gcflags=-m:package main import "fmt" func onStack() int { x := 42 // a plain local value: lives in this call's frame return x } func escapes() *int { y := 42 return &y // the caller still needs y after we return, so Go puts it on the heap } func main() { fmt.Println(onStack(), *escapes()) }Compiler output (extra lines trimmed):
./main.go:11:2: moved to heap: y
xstays in the frame;yis moved to the heap becauseescapeshands its address back to the caller. This is also why the benchmark above showedFibMemomaking allocations (its map lives on the heap) whileFibItermade none (two integers in a frame). Careful: it is not simply "local variables go on the stack, everything else on the heap". A local value that escapes goes to the heap, and a Go goroutine's stack starts small and grows automatically as the recursion gets deeper.
What if the base case is wrong? Remove it and run. Go grows a goroutine's stack up to 1 GB on 64-bit systems, so the program runs for a moment and then dies with runtime: goroutine stack exceeds 1000000000-byte limit and fatal error: stack overflow. This cannot be caught with recover, so students must get the base case right.
Here is the program with no base case. (Run it only on purpose; it will crash.)
package main
import "fmt"
// DANGER: no base case, so it never stops calling itself.
func countDown(n int) int {
return countDown(n-1) + 1
}
func main() {
fmt.Println("starting...")
fmt.Println(countDown(10))
}The first lines of what Go prints (the full message is about 270 lines of a stack trace):
Output
starting...
runtime: goroutine stack exceeds 1000000000-byte limit
runtime: sp=0x37b7f6280398 stack=[0x37b7f6280000, 0x37b816280000]
fatal error: stack overflow
...A sketch of what happened in memory:
THE STACK (one goroutine) THE HEAP
┌─────────────────────────────┐ (not involved here:
│ countDown(n = -3 ...) <-- newest frame nothing was allocated
│ countDown(n = -2) │ except the stack itself)
│ countDown(n = -1) │
│ countDown(n = 0) │
│ countDown(n = 10) │ <-- first call
│ main() │
└─────────────────────────────┘
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ← room left, up to the limit
━━━━━━━ 1,000,000,000 bytes ━━━━━━━ limit. One more frame:
fatal error: stack overflow (the program stops; recover() cannot help)Because every frame is small, a lot of them fit. On the box used for this guide, a harmless recursion of depth 10,000,000 used about 134 MB of stack and still worked:
package main
import (
"fmt"
"runtime"
)
func depth(n int) int {
if n == 0 {
return 0
}
return depth(n-1) + 1
}
func main() {
var ms runtime.MemStats
for _, d := range []int{1000, 100000, 1000000, 10000000} {
depth(d)
runtime.ReadMemStats(&ms)
fmt.Printf("recursion depth %-9d -> stack in use so far: about %d MB\n", d, ms.StackInuse/1000000)
}
}Output
recursion depth 1000 -> stack in use so far: about 0 MB
recursion depth 100000 -> stack in use so far: about 2 MB
recursion depth 1000000 -> stack in use so far: about 17 MB
recursion depth 10000000 -> stack in use so far: about 134 MB(Numbers depend on the machine and on how big each frame is. Do not rely on a specific depth limit; rely on the rule: recursion that is as deep as the input is a risk when the input can be huge.)
NewNew — recursion versus iteration (loop): the basic trade-off. Anything you can write with recursion you can also write with a loop, and the reverse. Recursion is usually shorter and mirrors the problem when the problem is made of smaller copies of itself (trees, folders inside folders, halving). A loop uses no extra stack frames and is usually a bit faster. You have already seen both:
FibNaive/FibMemoare recursive,FibIteris a loop. We will return to this after the string-reversal problem.
Bridge. So far recursion looked like a trap: FibNaive was slow and a missing base case crashes the program. But recursion is also a way to make programs dramatically faster, if each call shrinks the problem a lot. The next problem does exactly that.
#Problem B1: Power
Statement. Power(x float64, n int) float64 computes x raised to n for any integer n, including negative. Power(2, 10) = 1024, Power(2, -2) = 0.25, Power(5, 0) = 1.
(x^n means x multiplied by itself n times. A negative exponent means "one over": 2^-2 = 1 / 2^2 = 0.25. Anything to the power 0 is 1.)
Students try first. A loop or recursion that multiplies n times: O(n). For n = 1,000,000,000 that is a billion multiplications.
func PowerLoop(x float64, n int) float64 {
if n < 0 {
x, n = 1/x, -n
}
result := 1.0
for i := 0; i < n; i++ {
result *= x
}
return result
}It is correct and simple. Our job is to be smarter than "multiply n times".
The concept. Halve the problem. x^10 = (x^5)^2, and x^5 = (x^2)^2 * x. Each step cuts n in half, so only about log₂(n) steps are needed.
Everyday picture. To compute 2^10 you could multiply ten 2s together. Or notice that 2^10 = 2^5 × 2^5. If you already know 2^5 = 32, a single multiplication (32 × 32) gives 1024. And 2^5 itself is 2^2 × 2^2 × 2. Always reuse the half you already computed.
x^10 = x^5 · x^5 (10 is even: no extra x)
x^5 = x^2 · x^2 · x (5 is odd: one extra x)
x^2 = x^1 · x^1 (2 is even)
x^1 = x^0 · x^0 · x = x (1 is odd; x^0 = 1 is the base case)NewNew — integer division in
n/2, and the odd-number trick. In Go, dividing twoints gives anintand drops the remainder:5/2is2, not2.5. The remainder is available separately asn%2(5%2is1). For an oddnthe "missing" half is exactly one extra factor ofx:x^5 = x^2 · x^2 · x. The snippet shows the pattern for the exact numbers in this problem:package main import "fmt" func main() { // Integer division throws away the remainder (no rounding). fmt.Println("10/2 =", 10/2, " 5/2 =", 5/2, " 1/2 =", 1/2, " 7/2 =", 7/2) fmt.Println("7%2 =", 7%2, "(the remainder: 1 means odd, 0 means even)") fmt.Println("7.0/2 =", 7.0/2, "(a float keeps the .5)") fmt.Println("-7/2 =", -7/2, "(Go truncates toward zero)") // Why Power can use n/2 for odd n: the "missing" half is the extra x. for _, n := range []int{10, 5, 2, 1} { fmt.Printf("n=%-2d n/2=%d n%%2=%d so x^%d = (x^%d)*(x^%d)", n, n/2, n%2, n, n/2, n/2) if n%2 == 1 { fmt.Printf(" * x") } fmt.Println() } }Output
10/2 = 5 5/2 = 2 1/2 = 0 7/2 = 3 7%2 = 1 (the remainder: 1 means odd, 0 means even) 7.0/2 = 3.5 (a float keeps the .5) -7/2 = -3 (Go truncates toward zero) n=10 n/2=5 n%2=0 so x^10 = (x^5)*(x^5) n=5 n/2=2 n%2=1 so x^5 = (x^2)*(x^2) * x n=2 n/2=1 n%2=0 so x^2 = (x^1)*(x^1) n=1 n/2=0 n%2=1 so x^1 = (x^0)*(x^0) * x
Solution.
func Power(x float64, n int) float64 {
if n < 0 {
return 1 / Power(x, -n)
}
if n == 0 {
return 1
}
half := Power(x, n/2)
if n%2 == 0 {
return half * half
}
return half * half * x
}Reading it: negative exponent → compute the positive one and take 1 / .... n == 0 → base case. Otherwise compute the answer for half the exponent once, store it in half, and square it (times one more x if n is odd).
Predict. How many calls to Power will Power(2, 10) make? (Is it 10? 5? 4?)
Trace for Power(2, 10):
Power(2,10)needsPower(2,5)Power(2,5)needsPower(2,2)Power(2,2)needsPower(2,1)Power(2,1)needsPower(2,0), which returns 1 (base case)- Unwinding:
Power(2,1) = 1*1*2 = 2(odd),Power(2,2) = 2*2 = 4,Power(2,5) = 4*4*2 = 32,Power(2,10) = 32*32 = 1024
The halving tree. Going down, n is cut in half each time (10 → 5 → 2 → 1 → 0). Going back up, each level squares the answer below it:
going down: n = 10 ──▶ n = 5 ──▶ n = 2 ──▶ n = 1 ──▶ n = 0 (base case)
│ returns 1
coming up: 1024 ◀── 32 ◀── 4 ◀── 2 ◀───────┘
=32·32 =4·4·2 =2·2 =1·1·2Let the computer print the same trace, with indentation for depth:
package main
import (
"fmt"
"strings"
)
var calls int
func Power(x float64, n int) float64 {
calls++
if n < 0 {
return 1 / Power(x, -n)
}
if n == 0 {
return 1
}
half := Power(x, n/2)
if n%2 == 0 {
return half * half
}
return half * half * x
}
// The classic mistake: two recursive calls per level.
func PowerSlow(x float64, n int) float64 {
calls++
if n == 0 {
return 1
}
if n%2 == 0 {
return PowerSlow(x, n/2) * PowerSlow(x, n/2)
}
return PowerSlow(x, n/2) * PowerSlow(x, n/2) * x
}
func PowerTrace(x float64, n, depth int) float64 {
pad := strings.Repeat(" ", depth)
fmt.Printf("%sPower(%v,%d) called\n", pad, x, n)
if n == 0 {
fmt.Printf("%s-> returns 1 (base case)\n", pad)
return 1
}
half := PowerTrace(x, n/2, depth+1)
result := half * half
if n%2 == 1 {
result *= x
}
fmt.Printf("%s-> Power(%v,%d) = %v\n", pad, x, n, result)
return result
}
func main() {
PowerTrace(2, 10, 0)
fmt.Println()
fmt.Printf("%-14s %-12s %s\n", "n", "Power calls", "PowerSlow calls")
for _, n := range []int{10, 100, 1000, 1000000, 1000000000} {
calls = 0
Power(2, n)
fast := calls
slow := "(too many to wait for)"
if n <= 1000000 {
calls = 0
PowerSlow(2, n)
slow = fmt.Sprint(calls)
}
fmt.Printf("%-14d %-12d %s\n", n, fast, slow)
}
}Output
Power(2,10) called
Power(2,5) called
Power(2,2) called
Power(2,1) called
Power(2,0) called
-> returns 1 (base case)
-> Power(2,1) = 2
-> Power(2,2) = 4
-> Power(2,5) = 32
-> Power(2,10) = 1024
n Power calls PowerSlow calls
10 5 31
100 8 255
1000 11 2047
1000000 21 2097151
1000000000 31 (too many to wait for)Only 5 calls instead of 10, and for n = 1,000,000,000 only about 30 calls (the table above shows 31: 30 halvings plus the base case).
NewNew — "calls" versus "depth". The
Powercalls come one after another in a chain, so the number of calls (5 forn=10) equals the stack depth (5 frames at once). InFibNaivethe calls form a tree, so the number of calls (millions) is far bigger than the depth (onlynframes at once). Time follows the number of calls; stack memory follows the depth.
The classic mistake. Writing Power(x, n/2) * Power(x, n/2) calls the function twice per level, which brings the cost back to O(n). Storing the result in half is essential. Ask students to explain why.
Why: each level now makes two calls instead of one. The chain becomes a tree that doubles at each level, exactly like FibNaive:
PowerSlow(x,2) 1 call
├─ PowerSlow(x,1) 2 calls
│ ├─ PowerSlow(x,0) 4 calls
│ └─ PowerSlow(x,0)
└─ PowerSlow(x,1)
├─ PowerSlow(x,0)
└─ PowerSlow(x,0) 7 calls in total, vs 3 with `half`With about log₂(n) levels and doubling at each level you get 2^(log₂ n) = n calls. The last two columns of the output above are proof: for n = 1,000,000, Power makes 21 calls while the "mistake" version makes 2,097,151 (≈ 2n). For n = 1,000,000,000 it would be about 2.1 billion calls, which is why the program prints "too many to wait for".
Tests: (2,10) → 1024, (2,0) → 1, (2,-2) → 0.25, (5,1) → 5, (0,5) → 0, (1.5,2) → 2.25, (2,30) → 1073741824. (Edge cases to mention: Power(0, -1) divides by zero and gives +Inf; and n = math.MinInt overflows when negated.)
Both edge cases, run for real:
package main
import (
"fmt"
"math"
)
func Power(x float64, n int) float64 {
if n < 0 {
return 1 / Power(x, -n)
}
if n == 0 {
return 1
}
half := Power(x, n/2)
if n%2 == 0 {
return half * half
}
return half * half * x
}
func main() {
fmt.Println("Power(0, -1) =", Power(0, -1))
n := math.MinInt
fmt.Println("-MinInt == MinInt ?", -n == n) // true: negating wraps around
fmt.Println("Power(2, MinInt) ...")
fmt.Println(Power(2, math.MinInt)) // never gets to the base case
}The output (the stack trace after the last line is trimmed):
Output
Power(0, -1) = +Inf
-MinInt == MinInt ? true
Power(2, MinInt) ...
runtime: goroutine stack exceeds 1000000000-byte limit
...For floating-point numbers, dividing by zero is not a crash in Go; it gives +Inf ("infinity"). The math.MinInt case is more dangerous than it sounds: -n wraps around back to the same negative number (the odometer again), so n < 0 is still true, the function calls itself with the same input forever, and you get the stack overflow from earlier.
Complexity: O(log n) time, O(log n) stack depth.
Bridge. Power used recursion to shrink the problem fast. The next problem has a natural-looking recursive solution that shrinks it slowly and secretly costs a lot, and then shows how to fix it. It also asks the harder question: is recursion even the right tool here?
#Problem B2: Reverse a string recursively
Statement. ReverseRecursive(s string) string with no loops.
(Reverse means "abc" becomes "cba".)
NewNew — strings, bytes and runes (why the code says
[]rune). A Gostringis a sequence of bytes. Plain English letters take one byte, but a letter likeétakes two. A rune is one character (technically one Unicode code point). Converting with[]rune(s)gives a slice with one slot per character, so we can index and swap safely.package main import "fmt" func main() { // Strings are bytes; runes are characters. "é" is 2 bytes but 1 rune. s := "héllo" fmt.Println("bytes:", len(s), " runes:", len([]rune(s))) // Version 1: slice off the first character each time (copies the rest) copied := 0 var rev func(string) string rev = func(s string) string { r := []rune(s) if len(r) <= 1 { return s } copied += len(r) - 1 // the work of making string(r[1:]) return rev(string(r[1:])) + string(r[0]) } fmt.Println(rev("abc")) for _, n := range []int{10, 100, 1000} { copied = 0 long := make([]rune, n) for i := range long { long[i] = 'a' } rev(string(long)) fmt.Printf("slicing version, n=%-5d characters copied=%d\n", n, copied) } // Version 2: two pointers, swap in place r := []rune("abcde") var swap func(i, j int) swap = func(i, j int) { if i >= j { fmt.Printf("i=%d j=%d -> stop (pointers met or crossed): %s\n", i, j, string(r)) return } r[i], r[j] = r[j], r[i] fmt.Printf("i=%d j=%d -> swap -> %s\n", i, j, string(r)) swap(i+1, j-1) } swap(0, len(r)-1) }Output
bytes: 6 runes: 5 cba slicing version, n=10 characters copied=45 slicing version, n=100 characters copied=4950 slicing version, n=1000 characters copied=499500 i=0 j=4 -> swap -> ebcda i=1 j=3 -> swap -> edcba i=2 j=2 -> stop (pointers met or crossed): edcba(The first line shows
bytes: 6 runes: 5for"héllo". The rest of this snippet is used below.) If we reversed bytes,éwould be torn in half and the output would be broken text. That is the point of the"héllo"test.
Everyday picture. A deck of cards. To reverse it, take the top card, reverse all the rest, and then put the first card at the bottom. "Reverse the rest" is the same job on a smaller deck, which is why this fits recursion.
First attempt (correct but slow).
func ReverseRecursive(s string) string {
r := []rune(s)
if len(r) <= 1 {
return s
}
return ReverseRecursive(string(r[1:])) + string(r[0])
}The idea: the reverse of a string is the reverse of everything after the first character, followed by the first character. Trace "abc": Rev("bc") + "a", where Rev("bc") = Rev("c") + "b" = "c" + "b" = "cb", so the result is "cba".
Rev("abc") = Rev("bc") + "a"
Rev("bc") = Rev("c") + "b"
Rev("c") = "c" <- base case (1 character)
= "c" + "b" = "cb"
= "cb" + "a" = "cba"The base case is len(r) <= 1: the empty string and a single character are their own reverse. (r[1:] means "from index 1 to the end": the slice without the first element.)
The picture. Every call builds a brand-new, slightly shorter string:
"abcde" copy 4 characters to make "bcde"
"bcde" copy 3 characters to make "cde"
"cde" copy 2 characters to make "de"
"de" copy 1 character to make "e"
"e" base case
4 + 3 + 2 + 1 = 10 copies for 5 charactersFor a string of n characters that is (n-1) + (n-2) + ... + 1 = n(n-1)/2 copies, which is about n²/2 and therefore O(n²). The snippet above measured it: 45 copies for n = 10, 4,950 for n = 100, 499,500 for n = 1,000. Ten times the length means about 100 times the work.
Better: recurse on indices and swap in place.
func reverseHelper(r []rune, i, j int) {
if i >= j {
return
}
r[i], r[j] = r[j], r[i]
reverseHelper(r, i+1, j-1)
}
func ReverseRecursive2(s string) string {
r := []rune(s)
reverseHelper(r, 0, len(r)-1)
return string(r)
}Instead of making smaller strings, keep one slice and two markers: i at the left end, j at the right end. Swap what they point at, move them toward each other, and stop when they meet. A slice shares its underlying storage when you pass it to a function, so every call works on the same characters (no copying).
"abcde" i=0, j=4 swap r[0] and r[4] [a b c d e] → [e b c d a]
^ ^
i=1, j=3 swap r[1] and r[3] [e b c d a] → [e d c b a]
^ ^
i=2, j=2 i >= j → STOP [e d c b a] (middle one stays)
^The snippet printed exactly these three states (ebcda, edcba, then stop).
Now every call does O(1) work, so the total is O(n), with O(n) stack depth. The base case is i >= j (the pointers met or crossed). This ties back to the two-index loop from week 1.
(It makes about n/2 calls, which is still O(n). Notice that odd-length strings stop with i == j (the middle character, which needs no swap) and even-length strings stop with i > j; i >= j handles both.)
Discussion answer. Why prefer the loop version in production Go? Go does not optimize tail calls, so a recursion of depth n uses n stack frames. A loop uses none. Recursion is still the clearest tool when the problem is naturally recursive (trees, backtracking), which is where it is headed.
(A tail call is a call that is the very last thing a function does, like reverseHelper(r, i+1, j-1). Some languages reuse the current frame for it; Go does not, so the stack still grows.)
NewNew — recursion versus iteration: a checklist. Choose recursion when: the problem is made of smaller copies of itself (folders, trees, halving), the depth is small (like
log ninPower), or the recursive version is much clearer. Choose a loop when: the depth would be as big as the input (like reversing a long string), speed and memory are tight, or a loop is just as clear. And whichever you pick: check the base case, and check that each call really gets smaller.
Tests: "", "a", "abc" → "cba", "héllo" → "olléh" (rune-safe), "abba".
Bridge to Block C. Look at what the last three problems taught us. In Block A we saw that repeating work is what makes a program slow. In Power we saw the opposite: cutting the problem in half every time makes a huge job tiny. So here is the natural next question: can we use halving on a problem where we cannot just throw half away? Sorting is exactly that problem. We cannot ignore half of the numbers, because every number has to end up in the right place. But maybe we can sort each half separately, and then combine the two sorted halves cheaply. That idea is merge sort, and it is Block C.
#Block C: Merge sort
Everyday picture. Your teacher hands you 1,000 exam papers in random order and asks for them sorted by score. Plan 1: take the first paper, find where it belongs among the others, insert it; take the second paper, and so on. By the end you have looked through the pile hundreds of thousands of times. Plan 2: split the pile in two and give each half to a friend. Each friend does the same thing with their pile (hand halves to more friends...). When the piles are tiny (one paper) they are trivially sorted. Then comes the nice part: combining two sorted piles is easy. Put them side by side, look at the top paper of each pile, take the lower score, repeat. You never have to search; you only ever look at two papers. Plan 2 is merge sort.
#Problem C1: Sort a million numbers
Statement. MergeSort(nums []int) []int returns a sorted copy of the input. ("Sorted" means smallest to largest. "A copy" means the function builds a new slice and the original nums is left exactly as it was.)
Students try first. Bubble sort, the one they remember. Before the code, the idea: walk along the slice comparing each pair of neighbours; if they are in the wrong order, swap them. The biggest number "bubbles" to the end like a bubble rising in water. One walk is called a pass. After pass 1 the largest element is in its final place, after pass 2 the two largest are, and so on.
func BubbleSort(nums []int) {
n := len(nums)
for i := 0; i < n-1; i++ {
swapped := false
for j := 0; j < n-1-i; j++ {
if nums[j] > nums[j+1] {
nums[j], nums[j+1] = nums[j+1], nums[j]
swapped = true
}
}
if !swapped {
break
}
}
}Notes on reading it: the outer loop i counts passes. The inner loop j walks the pairs (nums[j], nums[j+1]), and stops at n-1-i because the last i elements are already final. swapped remembers whether this pass changed anything: if not, the slice is sorted and we can stop early. Unlike MergeSort, this function sorts in place: it changes the slice you give it and returns nothing.
Predict. Sort [5 1 4 2 8] by hand with bubble sort. How many passes before it stops? Then check:
package main
import "fmt"
func main() {
nums := []int{5, 1, 4, 2, 8}
n := len(nums)
fmt.Println("start:", nums)
for i := 0; i < n-1; i++ {
swapped := false
for j := 0; j < n-1-i; j++ {
if nums[j] > nums[j+1] {
x, y := nums[j], nums[j+1]
nums[j], nums[j+1] = y, x
fmt.Printf(" pass %d: compare %d and %d -> swap -> %v\n", i+1, x, y, nums)
swapped = true
} else {
fmt.Printf(" pass %d: compare %d and %d -> keep\n", i+1, nums[j], nums[j+1])
}
}
fmt.Printf("after pass %d: %v (the last %d element(s) are now final)\n", i+1, nums, i+1)
if !swapped {
fmt.Println("no swaps in this pass: already sorted, stop early")
break
}
}
}Output
start: [5 1 4 2 8]
pass 1: compare 5 and 1 -> swap -> [1 5 4 2 8]
pass 1: compare 5 and 4 -> swap -> [1 4 5 2 8]
pass 1: compare 5 and 2 -> swap -> [1 4 2 5 8]
pass 1: compare 5 and 8 -> keep
after pass 1: [1 4 2 5 8] (the last 1 element(s) are now final)
pass 2: compare 1 and 4 -> keep
pass 2: compare 4 and 2 -> swap -> [1 2 4 5 8]
pass 2: compare 4 and 5 -> keep
after pass 2: [1 2 4 5 8] (the last 2 element(s) are now final)
pass 3: compare 1 and 2 -> keep
pass 3: compare 2 and 4 -> keep
after pass 3: [1 2 4 5 8] (the last 3 element(s) are now final)
no swaps in this pass: already sorted, stop earlyThe same thing as a table (after pass k, the last k elements are already in their final place):
| After | Slice |
|---|---|
| start | 5 1 4 2 8 |
| pass 1 | 1 4 2 5 8 |
| pass 2 | 1 2 4 5 8 |
| pass 3 | no swaps: 1 2 4 5 8, stop |
The wall. For 10,000 numbers it takes a fraction of a second. For 1,000,000 numbers it needs roughly 500 billion comparisons (n²/2), which is many minutes. The swapped flag makes an already-sorted input O(n), but the worst and average cases stay O(n²).
Let the computer count comparisons instead of trusting the formula. This version adds a counter and tries three kinds of input: already sorted, random, and reversed (the worst case). This is also the "best, worst and average case" idea from Block A in action:
package main
import (
"fmt"
"math/rand"
)
var comparisons int
func BubbleSort(nums []int) {
n := len(nums)
for i := 0; i < n-1; i++ {
swapped := false
for j := 0; j < n-1-i; j++ {
comparisons++
if nums[j] > nums[j+1] {
nums[j], nums[j+1] = nums[j+1], nums[j]
swapped = true
}
}
if !swapped {
break
}
}
}
func run(name string, data []int) {
comparisons = 0
BubbleSort(data)
fmt.Printf(" %-9s %9d comparisons\n", name, comparisons)
}
func main() {
rng := rand.New(rand.NewSource(1))
for _, n := range []int{1000, 2000, 4000} {
fmt.Println("n =", n, " (n*n/2 =", n*n/2, ")")
random := make([]int, n)
sorted := make([]int, n)
reversed := make([]int, n)
for i := 0; i < n; i++ {
random[i] = rng.Int()
sorted[i] = i
reversed[i] = n - i
}
run("sorted", sorted)
run("random", random)
run("reversed", reversed)
}
}Output
n = 1000 (n*n/2 = 500000 )
sorted 999 comparisons
random 497420 comparisons
reversed 499500 comparisons
n = 2000 (n*n/2 = 2000000 )
sorted 1999 comparisons
random 1998700 comparisons
reversed 1999000 comparisons
n = 4000 (n*n/2 = 8000000 )
sorted 3999 comparisons
random 7997220 comparisons
reversed 7998000 comparisonsRead it like this: sorted input needs only n - 1 comparisons (one pass, no swaps, stop: O(n)). Random and reversed input need almost exactly n*n/2 comparisons, and doubling n multiplies them by 4 (500,000 → 2,000,000 → 8,000,000). That is the signature of O(n²).
Here is what that means for bigger inputs, using the formulas (bubble sort n²/2 comparisons, merge sort about n·log₂(n)), at an assumed 1 billion simple steps per second:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Printf("%-10s %-18s %-16s %s\n", "n", "bubble n*n/2", "merge n*log2(n)", "ratio")
for _, n := range []int{1000, 10000, 100000, 1000000} {
f := float64(n)
bub := f * f / 2
mer := f * math.Log2(f)
fmt.Printf("%-10d %-18.0f %-16.0f %.0fx\n", n, bub, mer, bub/mer)
}
fmt.Println()
fmt.Println("at 1 billion simple steps per second:")
for _, n := range []int{10000, 1000000} {
f := float64(n)
fmt.Printf(" n=%-8d bubble: %.4f s merge sort: %.4f s\n", n, f*f/2/1e9, f*math.Log2(f)/1e9)
}
}Output
n bubble n*n/2 merge n*log2(n) ratio
1000 500000 9966 50x
10000 50000000 132877 376x
100000 5000000000 1660964 3010x
1000000 500000000000 19931569 25086x
at 1 billion simple steps per second:
n=10000 bubble: 0.0500 s merge sort: 0.0001 s
n=1000000 bubble: 500.0000 s merge sort: 0.0199 sFor a million numbers: about 500 seconds (8 minutes) versus 0.02 seconds. And the gap gets wider as n grows.
NewNew — measuring versus counting. Counting comparisons gives a perfect "4×" every time we double
n. Measured time is messier, because it also depends on the hardware. On the machine used to check this guide, timingBubbleSorton random data gave:Output
n=2500 2.74ms n=5000 10.256ms (3.7x the previous row) n=10000 43.108ms (4.2x the previous row) n=20000 333.644ms (7.7x the previous row) n=40000 1.706097s (5.1x the previous row)Most steps are in the 4× to 5× range, but 10,000 → 20,000 jumped to nearly 8×, and
go test -benchrepeated that (about 40 ms versus 325 ms, five runs each). The comparison count still quadruples exactly, so the extra time must come from the machine (for example caches and branch prediction), not from the algorithm; I did not investigate which. The lesson: Big O predicts the shape of growth, and real timings follow it only roughly, so measure several sizes before drawing a conclusion.
Bridge. Bubble sort is slow because every element is compared with many others, one by one. The exam-paper story suggests another route: make the pile smaller before doing any real work. That is a general technique, and it has a name.
The concept: divide and conquer.
NewNew — divide and conquer. Solve a big problem by (1) dividing it into smaller copies of the same problem, (2) conquering each small copy (usually by recursion), and (3) combining the small answers into the big answer.
Powerwas a very lazy form of it (only one half needed solving). Merge sort needs both halves.
- Divide: split the slice in two halves.
- Conquer: sort each half recursively (a slice of 0 or 1 elements is already sorted: the base case).
- Combine: merge two sorted halves into one sorted slice. Merging is easy: keep a pointer into each half and repeatedly take the smaller front element.
(A pointer here just means "a position marker": an index like i or j that says which element of a slice we are looking at. It is the two-index idea from the reverse-a-string problem.)
Merging, traced. Merge [3 9] and [10 82]: compare 3 and 10, take 3; compare 9 and 10, take 9; the first half is empty, so append the rest of the second half: [3 9 10 82]. Each element is touched once, so merging is O(n).
As a picture, with the two pointers i (in a) and j (in b) and the output being built:
a = [3 9] b = [10 82] out = []
^i ^j
compare 3 <= 10 -> take 3 from a out = [3]
^i ^j
compare 9 <= 10 -> take 9 from a out = [3 9]
^i (past the end) ^j
a is used up -> append what is left of b: out = [3 9 10 82]Predict. What does Merge([2 5], [2 7]) return, and which 2 comes first in the output (the one from a or from b)? The next snippet prints each decision:
package main
import "fmt"
func Merge(a, b []int) []int {
out := make([]int, 0, len(a)+len(b))
i, j := 0, 0
for i < len(a) && j < len(b) {
if a[i] <= b[j] {
fmt.Printf(" compare %d and %d -> take %d from a\n", a[i], b[j], a[i])
out = append(out, a[i])
i++
} else {
fmt.Printf(" compare %d and %d -> take %d from b\n", a[i], b[j], b[j])
out = append(out, b[j])
j++
}
}
fmt.Printf(" loop over. leftover a: %v, leftover b: %v\n", a[i:], b[j:])
out = append(out, a[i:]...)
out = append(out, b[j:]...)
return out
}
func main() {
fmt.Println("Merge([3 9], [10 82]):")
fmt.Println("result:", Merge([]int{3, 9}, []int{10, 82}))
fmt.Println()
fmt.Println("Merge([2 5], [2 7]) (equal heads):")
fmt.Println("result:", Merge([]int{2, 5}, []int{2, 7}))
}Output
Merge([3 9], [10 82]):
compare 3 and 10 -> take 3 from a
compare 9 and 10 -> take 9 from a
loop over. leftover a: [], leftover b: [10 82]
result: [3 9 10 82]
Merge([2 5], [2 7]) (equal heads):
compare 2 and 2 -> take 2 from a
compare 5 and 2 -> take 2 from b
compare 5 and 7 -> take 5 from a
loop over. leftover a: [], leftover b: [7]
result: [2 2 5 7]Solution.
func Merge(a, b []int) []int {
out := make([]int, 0, len(a)+len(b))
i, j := 0, 0
for i < len(a) && j < len(b) {
if a[i] <= b[j] {
out = append(out, a[i])
i++
} else {
out = append(out, b[j])
j++
}
}
out = append(out, a[i:]...)
out = append(out, b[j:]...)
return out
}
func MergeSort(nums []int) []int {
if len(nums) <= 1 {
return slices.Clone(nums)
}
mid := len(nums) / 2
left := MergeSort(nums[:mid])
right := MergeSort(nums[mid:])
return Merge(left, right)
}Details.
a[i] <= b[j](not<) takes from the left half on ties, which keeps equal elements in their original order. That makes merge sort stable.outis allocated once with capacitylen(a)+len(b), soappendnever reallocates.- The two trailing appends handle the leftovers: when the loop ends, at least one half is exhausted, so one of those appends adds nothing.
nums[:mid]andnums[mid:]are windows on the same array (week 2), but sinceMergeSortnever modifies its input, sharing is safe.slices.Clonein the base case guarantees the result never aliases the input.
NewNew — reading the slice syntax.
nums[:mid]means "the elements from the start up to (not including) indexmid", andnums[mid:]means "from indexmidto the end". Together they cover everything exactly once.mid := len(nums) / 2uses integer division (the samen/2as inPower): for 7 elementsmidis 3, so the left half gets 3 and the right half gets 4. The...inappend(out, a[i:]...)means "append all the elements of this slice, one by one" (without it, Go would try to append the slice itself as a single element and refuse to compile).
NewNew — what "stable" means, and why
<=matters. A sort is stable if elements that compare equal stay in their original order. That matters when you sort records by one field and want an earlier ordering to survive: for example sorting students by grade, keeping alphabetical order inside each grade. In the program below the two items with key 2 are labelled so we can see which one comes first:package main import "fmt" type item struct { key int name string } func mergeBy(a, b []item, takeLeftOnTie bool) []item { var out []item i, j := 0, 0 for i < len(a) && j < len(b) { left := a[i].key < b[j].key || (takeLeftOnTie && a[i].key == b[j].key) if left { out = append(out, a[i]) i++ } else { out = append(out, b[j]) j++ } } out = append(out, a[i:]...) return append(out, b[j:]...) } func main() { a := []item{{2, "first 2"}, {5, "a5"}} b := []item{{2, "second 2"}, {7, "b7"}} fmt.Println("with <= (take from the left on ties):", mergeBy(a, b, true)) fmt.Println("with < (take from the right on ties):", mergeBy(a, b, false)) }Output
with <= (take from the left on ties): [{2 first 2} {2 second 2} {5 a5} {7 b7}] with < (take from the right on ties): [{2 second 2} {2 first 2} {5 a5} {7 b7}]With
<=the "first 2" (from the left half) stays in front. With<they swap places: still sorted by key, but no longer stable.
Full trace for [38 27 43 3 9 82 10]:
split: [38 27 43 3 9 82 10]
[38 27 43] [3 9 82 10]
[38] [27 43] [3 9] [82 10]
[27] [43] [3] [9] [82] [10]
merge: [27 43] [3 9] [10 82]
[27 38 43] [3 9 10 82]
[3 9 10 27 38 43 82]The same tree as a diagram (green boxes are pieces that still get split; yellow boxes are single-element pieces, the base case; the merging happens on the way back up, as in the trace above):
Here the computer prints the same thing, with the merges, and counts the comparisons made while merging:
package main
import (
"fmt"
"slices"
"strings"
)
var comparisons int
func Merge(a, b []int) []int {
out := make([]int, 0, len(a)+len(b))
i, j := 0, 0
for i < len(a) && j < len(b) {
comparisons++
if a[i] <= b[j] {
out = append(out, a[i])
i++
} else {
out = append(out, b[j])
j++
}
}
out = append(out, a[i:]...)
out = append(out, b[j:]...)
return out
}
func MergeSortTrace(nums []int, depth int) []int {
pad := strings.Repeat(" ", depth)
fmt.Printf("%ssplit %v\n", pad, nums)
if len(nums) <= 1 {
return slices.Clone(nums)
}
mid := len(nums) / 2
left := MergeSortTrace(nums[:mid], depth+1)
right := MergeSortTrace(nums[mid:], depth+1)
merged := Merge(left, right)
fmt.Printf("%smerge %v + %v -> %v\n", pad, left, right, merged)
return merged
}
func main() {
fmt.Println(MergeSortTrace([]int{38, 27, 43, 3, 9, 82, 10}, 0))
fmt.Println("comparisons made while merging:", comparisons)
}Output
split [38 27 43 3 9 82 10]
split [38 27 43]
split [38]
split [27 43]
split [27]
split [43]
merge [27] + [43] -> [27 43]
merge [38] + [27 43] -> [27 38 43]
split [3 9 82 10]
split [3 9]
split [3]
split [9]
merge [3] + [9] -> [3 9]
split [82 10]
split [82]
split [10]
merge [82] + [10] -> [10 82]
merge [3 9] + [10 82] -> [3 9 10 82]
merge [27 38 43] + [3 9 10 82] -> [3 9 10 27 38 43 82]
[3 9 10 27 38 43 82]
comparisons made while merging: 13Notice the order: the left half is completely finished (split, then merged) before the right half starts. That is the call stack at work: while the left half is being sorted, the call for the whole slice just waits.
Complexity: why O(n log n). The slice is halved until pieces have one element, which takes about log₂(n) levels (20 levels for a million items). At each level the merges together touch all n elements once: O(n) per level. So the total is O(n log n). For one million numbers that is about 20 million steps instead of 500 billion. It needs O(n) extra space for the merged slices. Compare with bubble sort: O(n²) time, O(1) space, which is the classic time-versus-space trade.
The same thing as a picture for n = 8 (each row is one level; every row touches all 8 numbers once):
level 0: [ 8 numbers ] merge work: 8
level 1: [ 4 numbers ] [ 4 numbers ] merge work: 4 + 4 = 8
level 2: [2][2] [2][2] merge work: 2+2+2+2 = 8
level 3: [1][1][1][1][1][1][1][1] (base case: no merging needed)
levels of merging = log2(8) = 3 work per level = 8 total = 8 x 3 = 24 stepsNewNew — "extra space" and "in place". A sort is in place if it rearranges the slice it is given and needs only a handful of extra variables (O(1) extra space): bubble sort and quick sort are. Merge sort builds new slices at every level, so while it runs it holds about
nextra numbers (O(n) extra space). "Extra" means: besides the input itself.
NewNew — merge sort's recursion is shallow. Compare with
FibNaive, whose call tree was huge. Merge sort's call tree has 2n - 1 calls (one per piece), but the depth (frames waiting on the stack at once) is only about log₂(n): 20 frames for a million numbers. That is why there is no stack overflow risk here, unlike reversing a long string recursively.
Bridge. We now have a function that we believe is correct, and a theory that says it is fast. Neither has been checked yet. The next two steps are exactly that: tests for correctness, benchmarks for speed.
Tests: compare against a trusted answer. A very effective technique is to test against the standard library on many random inputs:
func TestMergeSortRandom(t *testing.T) {
rng := rand.New(rand.NewSource(1))
for trial := 0; trial < 200; trial++ {
n := rng.Intn(100)
in := make([]int, n)
for i := range in {
in[i] = rng.Intn(50) - 25
}
want := slices.Clone(in)
sort.Ints(want)
got := MergeSort(slices.Clone(in))
if !slices.Equal(got, want) {
t.Fatalf("input %v: got %v, want %v", in, got, want)
}
}
}NewNew — what the random test is doing.
rand.NewSource(1)is a seed: the same seed always produces the same "random" numbers, so a failure can be reproduced exactly (run it again and you get the same bad input). Each trial builds a random slice of length 0 to 99 with values from -25 to 24 (so there are many duplicates, which is where sorting bugs hide), asks the standard librarysort.Intsfor the right answer, and compares. We clone the input before passing it so the test also catches a function that changes its input.t.Fatalfstops the test and prints the input that broke it.
Also add a table test for the fixed edge cases: nil, [], [5], [2 1], [1 2 3] (already sorted), [3 2 1] (reverse), [2 2 2] (all equal), [3 -1 0 -5] (negatives), and [1 3 2 3 1] (duplicates). The random test uses a fixed seed, so a failure is reproducible.
var sortCases = []struct {
name string
in []int
want []int
}{
{"nil", nil, []int{}},
{"empty", []int{}, []int{}},
{"single", []int{5}, []int{5}},
{"two reversed", []int{2, 1}, []int{1, 2}},
{"already sorted", []int{1, 2, 3}, []int{1, 2, 3}},
{"reverse", []int{3, 2, 1}, []int{1, 2, 3}},
{"all equal", []int{2, 2, 2}, []int{2, 2, 2}},
{"negatives", []int{3, -1, 0, -5}, []int{-5, -1, 0, 3}},
{"duplicates", []int{1, 3, 2, 3, 1}, []int{1, 1, 2, 3, 3}},
{"trace example", []int{38, 27, 43, 3, 9, 82, 10}, []int{3, 9, 10, 27, 38, 43, 82}},
}The test function that runs the table (it checks MergeSort, that it did not change its input, and also BubbleSort and QuickSort against the same table, so one table checks all three sorts):
func TestSortEdgeCases(t *testing.T) {
for _, tc := range sortCases {
t.Run(tc.name, func(t *testing.T) {
in := slices.Clone(tc.in)
got := MergeSort(in)
if !slices.Equal(got, tc.want) {
t.Errorf("MergeSort(%v) = %v, want %v", tc.in, got, tc.want)
}
if !slices.Equal(in, tc.in) && !(tc.in == nil && len(in) == 0) {
t.Errorf("MergeSort changed its input: %v -> %v", tc.in, in)
}
b := slices.Clone(tc.in)
BubbleSort(b)
if len(b) != len(tc.want) || (len(b) > 0 && !slices.Equal(b, tc.want)) {
t.Errorf("BubbleSort(%v) = %v, want %v", tc.in, b, tc.want)
}
q := slices.Clone(tc.in)
QuickSort(q)
if len(q) != len(tc.want) || (len(q) > 0 && !slices.Equal(q, tc.want)) {
t.Errorf("QuickSort(%v) = %v, want %v", tc.in, q, tc.want)
}
})
}
}(t.Run(name, ...) runs each row as its own named sub-test, so a failure tells you which row broke. Go's slices.Equal treats nil and []int{} as equal, because it compares lengths and elements.) The package also tests Merge([3 9], [10 82]), stability on records, and that MergeSort leaves its input unchanged. Run everything with go test -v ./...; all of it passes.
Benchmarks.
func benchData(n int) []int {
rng := rand.New(rand.NewSource(42))
data := make([]int, n)
for i := range data {
data[i] = rng.Int()
}
return data
}
func BenchmarkMergeSort(b *testing.B) {
data := benchData(100000)
b.ResetTimer()
for i := 0; i < b.N; i++ {
MergeSort(slices.Clone(data))
}
}
func BenchmarkSortInts(b *testing.B) {
data := benchData(100000)
b.ResetTimer()
for i := 0; i < b.N; i++ {
sort.Ints(slices.Clone(data))
}
}(b.ResetTimer() restarts the clock after the setup, so building the data is not counted. slices.Clone(data) gives each run a fresh unsorted copy; both benchmarks pay for the same clone.) Expect the standard library to be faster than the hand-written merge sort (it sorts in place and is heavily tuned) and -benchmem to show merge sort allocating a lot. The takeaway: write your own to learn, use the standard library in real projects, and remember that both are O(n log n), so they scale the same way. Also benchmark BubbleSort at 10,000 and 20,000 elements: doubling the input roughly quadruples the time, the signature of O(n²).
func benchBubble(b *testing.B, n int) {
data := benchData(n)
b.ResetTimer()
for i := 0; i < b.N; i++ {
BubbleSort(slices.Clone(data))
}
}
func BenchmarkBubbleSort10k(b *testing.B) { benchBubble(b, 10000) }
func BenchmarkBubbleSort20k(b *testing.B) { benchBubble(b, 20000) }Real output from go test -bench='MergeSort|SortInts|QuickSort|Bubble' -benchmem -run='^$' on the machine used to check this guide (the QuickSort... lines are explained in the optional section below):
Output
goos: linux
goarch: amd64
pkg: week4/week4
cpu: Intel(R) Xeon(R) Processor
BenchmarkMergeSort-8 72 15715415 ns/op 15661068 B/op 200003 allocs/op
BenchmarkSortInts-8 178 6741345 ns/op 802821 B/op 1 allocs/op
BenchmarkQuickSort-8 201 5488842 ns/op 802821 B/op 1 allocs/op
BenchmarkBubbleSort10k-8 30 41008207 ns/op 81920 B/op 1 allocs/op
BenchmarkBubbleSort20k-8 4 322760482 ns/op 163840 B/op 1 allocs/op
BenchmarkQuickSortSorted10k-8 43 27455842 ns/op 81920 B/op 1 allocs/op
BenchmarkQuickSortSorted20k-8 9 114797278 ns/op 163840 B/op 1 allocs/op
PASS
ok week4/week4 11.708sHow to read it (same columns as in Block A):
| Comparison | Numbers | What it shows |
|---|---|---|
MergeSort vs sort.Ints, 100,000 numbers | 15.7 ms vs 6.7 ms | The standard library is about 2.3× faster, but both are in the same family (milliseconds for 100,000 numbers). |
| Allocations | 15,661,068 B and 200,003 allocs vs 802,821 B and 1 alloc | Merge sort allocates about 20× more memory and makes 200,003 allocations (a new slice for every merge). sort.Ints allocates only the clone we gave it. |
BubbleSort 10k vs 20k | 41.0 ms vs 322.8 ms | Quadratic growth: the comparisons are exactly 4× more; the measured time here was 7.9× (see the note above about hardware effects). |
BubbleSort 10k vs MergeSort 100k | 41 ms vs 15.7 ms | Merge sort sorts ten times more numbers in well under half the time. |
Summary of C1.
| BubbleSort | MergeSort | |
|---|---|---|
| Idea | bubble the biggest to the end, repeat | split, sort halves, merge |
| Time | O(n²) (O(n) if already sorted) | O(n log n) always |
| Extra space | O(1) (in place) | O(n) |
| Stable | yes | yes (with <=) |
| Recursion depth | none (loops) | about log₂(n) |
#Optional reading: quick sort
Everyday picture. A teacher lines up children by height. She picks one child, the pivot, and says: "shorter children to my left, taller to my right." After that the pivot is in its final place. Then each side, which is a smaller line, gets the same treatment, again and again. That is quick sort: where merge sort does its work after the recursive calls (merging), quick sort does it before (partitioning).
Quick sort picks a pivot, moves smaller elements to its left and larger ones to its right (partitioning), then recursively sorts both sides:
func QuickSort(a []int) {
if len(a) < 2 {
return
}
p := a[len(a)-1] // pivot: last element
i := 0
for j := 0; j < len(a)-1; j++ {
if a[j] < p {
a[i], a[j] = a[j], a[i]
i++
}
}
a[i], a[len(a)-1] = a[len(a)-1], a[i]
QuickSort(a[:i])
QuickSort(a[i+1:])
}How the loop works: i marks the boundary between "smaller than the pivot" (everything left of i) and "not yet known or larger" (from i on). j scans forward. When a[j] is smaller than the pivot, we swap it into slot i and move the boundary. At the end the pivot is swapped into slot i, its final place. Here is one partition, traced, on [8 3 7 1 5 4], and then the same on an already-sorted slice:
package main
import (
"fmt"
"math/rand"
)
var comparisons, maxDepth int
func QuickSort(a []int, depth int) {
if depth > maxDepth {
maxDepth = depth
}
if len(a) < 2 {
return
}
p := a[len(a)-1] // pivot: last element
i := 0
for j := 0; j < len(a)-1; j++ {
comparisons++
if a[j] < p {
a[i], a[j] = a[j], a[i]
i++
}
}
a[i], a[len(a)-1] = a[len(a)-1], a[i]
QuickSort(a[:i], depth+1)
QuickSort(a[i+1:], depth+1)
}
func partitionTrace(a []int) {
p := a[len(a)-1]
fmt.Printf("array %v, pivot = %d (last element)\n", a, p)
i := 0
for j := 0; j < len(a)-1; j++ {
if a[j] < p {
a[i], a[j] = a[j], a[i]
fmt.Printf(" j=%d: %d < %d -> swap into slot i=%d -> %v\n", j, a[i], p, i, a)
i++
} else {
fmt.Printf(" j=%d: %d >= %d -> leave it\n", j, a[j], p)
}
}
a[i], a[len(a)-1] = a[len(a)-1], a[i]
fmt.Printf(" put the pivot in slot i=%d -> %v (left: %v, right: %v)\n", i, a, a[:i], a[i+1:])
}
func measure(name string, data []int) {
comparisons, maxDepth = 0, 0
QuickSort(data, 0)
fmt.Printf(" %-9s comparisons=%-8d deepest recursion=%d\n", name, comparisons, maxDepth)
}
func main() {
partitionTrace([]int{8, 3, 7, 1, 5, 4})
fmt.Println()
partitionTrace([]int{1, 2, 3, 4, 5, 6})
fmt.Println()
rng := rand.New(rand.NewSource(1))
for _, n := range []int{500, 1000, 2000} {
random := make([]int, n)
sorted := make([]int, n)
for i := range random {
random[i] = rng.Int()
sorted[i] = i
}
fmt.Println("n =", n)
measure("random", random)
measure("sorted", sorted)
}
}Output
array [8 3 7 1 5 4], pivot = 4 (last element)
j=0: 8 >= 4 -> leave it
j=1: 3 < 4 -> swap into slot i=0 -> [3 8 7 1 5 4]
j=2: 7 >= 4 -> leave it
j=3: 1 < 4 -> swap into slot i=1 -> [3 1 7 8 5 4]
j=4: 5 >= 4 -> leave it
put the pivot in slot i=2 -> [3 1 4 8 5 7] (left: [3 1], right: [8 5 7])
array [1 2 3 4 5 6], pivot = 6 (last element)
j=0: 1 < 6 -> swap into slot i=0 -> [1 2 3 4 5 6]
j=1: 2 < 6 -> swap into slot i=1 -> [1 2 3 4 5 6]
j=2: 3 < 6 -> swap into slot i=2 -> [1 2 3 4 5 6]
j=3: 4 < 6 -> swap into slot i=3 -> [1 2 3 4 5 6]
j=4: 5 < 6 -> swap into slot i=4 -> [1 2 3 4 5 6]
put the pivot in slot i=5 -> [1 2 3 4 5 6] (left: [1 2 3 4 5], right: [])
n = 500
random comparisons=5640 deepest recursion=19
sorted comparisons=124750 deepest recursion=499
n = 1000
random comparisons=11394 deepest recursion=24
sorted comparisons=499500 deepest recursion=999
n = 2000
random comparisons=22555 deepest recursion=20
sorted comparisons=1999000 deepest recursion=1999Average time is O(n log n) and it sorts in place, but with the last element as pivot an already sorted input is the worst case: O(n²) time and deep recursion. Real implementations pick a random or median pivot. It is not stable.
Why sorted input is the worst case: the pivot is the largest element, so nothing goes to the right and n - 1 elements go to the left. Each call only removes one element, so the recursion goes n levels deep instead of about log n, and the comparisons add up to (n-1) + (n-2) + ... + 1, about n²/2. The last table in the output above shows exactly that: for n = 2,000 the random input needs 22,555 comparisons and a recursion 20 deep, but the sorted input needs 1,999,000 comparisons and a recursion 1,999 deep. The benchmarks agree: sorting 10,000 already-sorted numbers took 27.5 ms and 20,000 took 114.8 ms (about 4.2×, quadratic), while sorting 100,000 random numbers took only 5.5 ms.
| MergeSort | QuickSort (last-element pivot) | |
|---|---|---|
| Average time | O(n log n) | O(n log n) |
| Worst time | O(n log n) | O(n²) (e.g. sorted input) |
| Extra space | O(n) | O(1) extra values, plus the recursion stack (log n on average, n worst case) |
| Stable | yes | no |
| Benchmark, 100,000 random numbers | 15.7 ms | 5.5 ms |
#Backtracking preview for tetris-optimizer (10 minutes, can be homework)
Everyday picture. You are in a maze with a piece of chalk. At each junction you choose a corridor and chalk an arrow on the floor. You explore it. If it is a dead end you walk back and undo: rub out the chalk arrow, so the junction is clean for the next try, and you pick the next corridor. When you find the exit, you stop. That is backtracking: try something, go deeper, and if it fails, take it back and try the next option.
Many search problems follow one template: choose, explore, undo.
func solve(state) bool {
if done(state) {
return true
}
for _, choice := range choices(state) {
apply(choice) // choose
if solve(state) { // explore
return true
}
undo(choice) // undo
}
return false
}(This is a template, not a runnable program: state, done, choices, apply and undo are placeholders for whatever your problem needs.)
A small worked example: generate every binary string of length n.
func Binary(n int) []string {
var res []string
cur := make([]byte, 0, n)
var gen func()
gen = func() {
if len(cur) == n {
res = append(res, string(cur)) // copies cur
return
}
for _, c := range []byte{'0', '1'} {
cur = append(cur, c) // choose
gen() // explore
cur = cur[:len(cur)-1] // undo
}
}
gen()
return res
}Binary(2) returns [00 01 10 11]. Two things to notice: string(cur) makes a copy (essential, because cur keeps being reused: this is the week 2 aliasing lesson again), and the undo step is what lets one slice serve every branch. In tetris-optimizer, a "choice" is placing a piece at a position, the "undo" removes it, and "done" means all pieces fit.
Predict. For Binary(2), how many times does the program "choose", and in what order do the results appear? Here is the full story of Binary(2), with every choose and undo printed (each indentation is one level deeper). The program then tries the same thing without the copy, to show what goes wrong:
package main
import "fmt"
func main() {
n := 2
var res []string
cur := make([]byte, 0, n)
var gen func(depth int)
gen = func(depth int) {
pad := ""
for i := 0; i < depth; i++ {
pad += " "
}
if len(cur) == n {
fmt.Printf("%sFULL LENGTH: save %q\n", pad, string(cur))
res = append(res, string(cur))
return
}
for _, c := range []byte{'0', '1'} {
cur = append(cur, c)
fmt.Printf("%schoose %q cur=%q\n", pad, c, cur)
gen(depth + 1)
cur = cur[:len(cur)-1]
fmt.Printf("%sundo %q cur=%q\n", pad, c, cur)
}
}
gen(0)
fmt.Println("result:", res)
// What if we forget the copy and store the slice itself?
var shared [][]byte
buf := make([]byte, 0, 2)
var gen2 func()
gen2 = func() {
if len(buf) == 2 {
shared = append(shared, buf) // NO copy: every entry points at the same memory
return
}
for _, c := range []byte{'0', '1'} {
buf = append(buf, c)
gen2()
buf = buf[:len(buf)-1]
}
}
gen2()
fmt.Print("without copying: ")
for _, s := range shared {
fmt.Printf("%q ", string(s))
}
fmt.Println()
}Output
choose '0' cur="0"
choose '0' cur="00"
FULL LENGTH: save "00"
undo '0' cur="0"
choose '1' cur="01"
FULL LENGTH: save "01"
undo '1' cur="0"
undo '0' cur=""
choose '1' cur="1"
choose '0' cur="10"
FULL LENGTH: save "10"
undo '0' cur="1"
choose '1' cur="11"
FULL LENGTH: save "11"
undo '1' cur="1"
undo '1' cur=""
result: [00 01 10 11]
without copying: "11" "11" "11" "11" Read the trace from top to bottom: choose '0', then (one level deeper) choose '0' gives "00", which is full length, so it is saved. undo removes the last '0', we try '1' and get "01"; then both choices at this level are used up, so we undo the first '0' and go to the other branch. The shape is a tree (below), and the program walks it depth first, one root-to-leaf path at a time. Without string(cur), all four stored entries point at the same memory and show the final contents of the buffer, "11" four times: the aliasing bug.
NewNew — why the answer count grows fast. Each position has 2 choices, so
Binary(n)returns2^nstrings (4 forn = 2, 8 forn = 3, over a million forn = 20). Backtracking explores a tree like this one, so it can be exponential, just likeFibNaivein Block A. Real backtracking solvers (tetris-optimizer included) prune: as soon as a placement cannot work, they undo it right away instead of exploring the whole sub-tree under it.
#Week 4 homework with answers
The answers are hidden: try each problem first.
1. Recursive digit sum (for n ≥ 0). Write DigitSumRec(n int) int that adds the digits of n using recursion and no loop. (Hint: n%10 is the last digit, n/10 is everything else.)
Show answer
func DigitSumRec(n int) int {
if n < 10 {
return n
}
return n%10 + DigitSumRec(n/10)
}DigitSumRec(4729) is 9 + DigitSumRec(472) = 9 + 2 + DigitSumRec(47) = ... = 22.
package main
import (
"fmt"
"strconv"
"strings"
)
func DigitSumRec(n, depth int) int {
pad := strings.Repeat(" ", depth)
if n < 10 {
fmt.Printf("%sDigitSumRec(%d) = %d (base case)\n", pad, n, n)
return n
}
fmt.Printf("%sDigitSumRec(%d) = %d + DigitSumRec(%d)\n", pad, n, n%10, n/10)
return n%10 + DigitSumRec(n/10, depth+1)
}
func ToBinary(n, depth int) string {
pad := strings.Repeat(" ", depth)
if n < 2 {
fmt.Printf("%sToBinary(%d) = %q (base case)\n", pad, n, strconv.Itoa(n))
return strconv.Itoa(n)
}
fmt.Printf("%sToBinary(%d) = ToBinary(%d) + %q\n", pad, n, n/2, strconv.Itoa(n%2))
return ToBinary(n/2, depth+1) + strconv.Itoa(n%2)
}
func main() {
fmt.Println("answer:", DigitSumRec(4729, 0))
fmt.Println()
fmt.Println("answer:", ToBinary(10, 0))
fmt.Println("check: ", strconv.FormatInt(10, 2))
}Output
DigitSumRec(4729) = 9 + DigitSumRec(472)
DigitSumRec(472) = 2 + DigitSumRec(47)
DigitSumRec(47) = 7 + DigitSumRec(4)
DigitSumRec(4) = 4 (base case)
answer: 22
ToBinary(10) = ToBinary(5) + "0"
ToBinary(5) = ToBinary(2) + "1"
ToBinary(2) = ToBinary(1) + "0"
ToBinary(1) = "1" (base case)
answer: 1010
check: 1010The base case is "a single digit is its own digit sum". The input shrinks by a factor of 10 each call, so the depth is the number of digits: O(log₁₀ n). The tests in the package check 0, 7, 10, 4729 and 99999. (The statement says n ≥ 0: for a negative n the first if would return it unchanged.)
2. Decimal to binary, recursively. Write ToBinary(n int) string. (Hint: the last binary digit is n%2; the rest is the binary form of n/2.)
Show answer
func ToBinary(n int) string {
if n < 2 {
return strconv.Itoa(n)
}
return ToBinary(n/2) + strconv.Itoa(n%2)
}ToBinary(10): ToBinary(5) + "0", where ToBinary(5) = ToBinary(2) + "1" and ToBinary(2) = ToBinary(1) + "0" = "10", so ToBinary(5) = "101" and ToBinary(10) = "1010". Check with strconv.FormatInt(10, 2). (The last line of the output above confirms it; the package test compares ToBinary with strconv.FormatInt for every n from 0 to 1,000. As in problem 1, n must be ≥ 0.)
3. Merge Sorted Array revisited. Solve it again using Merge from this session, then compare with the in-place back-to-front solution from week 2. Which uses less memory?
Show answer
Merge(nums1[:m], nums2) solves it in one line and returns a new slice (then copy it back into nums1 if the problem demands in-place output). It is O(m + n) time but needs O(m + n) extra memory for the new slice. The week 2 back-to-front solution fills nums1 from the end, writing the largest elements first so nothing unread is overwritten: O(m + n) time and O(1) extra memory. So the in-place solution uses less memory; Merge is shorter and clearer.
4. Stretch: count inversions (pairs i < j where nums[i] > nums[j]), by extending merge sort. (Hint: an inversion is exactly a time when merging takes from the right half while elements are still waiting in the left half.)
Show answer
func CountInversions(nums []int) ([]int, int) {
if len(nums) <= 1 {
return slices.Clone(nums), 0
}
mid := len(nums) / 2
left, lc := CountInversions(nums[:mid])
right, rc := CountInversions(nums[mid:])
inv := lc + rc
merged := make([]int, 0, len(nums))
i, j := 0, 0
for i < len(left) && j < len(right) {
if left[i] <= right[j] {
merged = append(merged, left[i])
i++
} else {
merged = append(merged, right[j])
j++
inv += len(left) - i
}
}
merged = append(merged, left[i:]...)
merged = append(merged, right[j:]...)
return merged, inv
}The key line is inv += len(left) - i: when a right element is smaller than left[i], it is also smaller than every remaining left element (they are all larger, because the left half is sorted). [2 4 1 3 5] has 3 inversions: (2,1), (4,1), (4,3). Brute force is O(n²); this is O(n log n).
package main
import (
"fmt"
"slices"
)
func CountInversions(nums []int) ([]int, int) {
if len(nums) <= 1 {
return slices.Clone(nums), 0
}
mid := len(nums) / 2
left, lc := CountInversions(nums[:mid])
right, rc := CountInversions(nums[mid:])
inv := lc + rc
merged := make([]int, 0, len(nums))
i, j := 0, 0
fmt.Printf("merge %v + %v\n", left, right)
for i < len(left) && j < len(right) {
if left[i] <= right[j] {
merged = append(merged, left[i])
i++
} else {
merged = append(merged, right[j])
fmt.Printf(" %d (right) < %d (left): it jumps over %d left element(s) -> +%d inversions\n", right[j], left[i], len(left)-i, len(left)-i)
j++
inv += len(left) - i
}
}
merged = append(merged, left[i:]...)
merged = append(merged, right[j:]...)
fmt.Printf(" -> %v, inversions so far in this range: %d\n", merged, inv)
return merged, inv
}
func main() {
sorted, inv := CountInversions([]int{2, 4, 1, 3, 5})
fmt.Println("sorted:", sorted, " inversions:", inv)
}Output
merge [2] + [4]
-> [2 4], inversions so far in this range: 0
merge [3] + [5]
-> [3 5], inversions so far in this range: 0
merge [1] + [3 5]
-> [1 3 5], inversions so far in this range: 0
merge [2 4] + [1 3 5]
1 (right) < 2 (left): it jumps over 2 left element(s) -> +2 inversions
3 (right) < 4 (left): it jumps over 1 left element(s) -> +1 inversions
-> [1 2 3 4 5], inversions so far in this range: 3
sorted: [1 2 3 4 5] inversions: 3The package test confirms [2 4 1 3 5] gives [1 2 3 4 5] and 3, and also compares the fast answer with a brute-force double loop on 200 random slices.
5. Big O practice. Write the complexity of FibIter, Merge, BubbleSort, binary search, and Power, with one sentence each.
Show answer
| Function | Complexity | One sentence |
|---|---|---|
FibIter | O(n) | one loop of n steps, constant work each |
Merge | O(n) | every element of both halves is taken exactly once (n = total size) |
BubbleSort | O(n²) | a loop inside a loop; about n²/2 comparisons |
| binary search | O(log n) | each step throws half of the remaining range away |
Power | O(log n) | each call halves the exponent (and stores the half result once) |
#Check for understanding (answers included)
Try to answer in your own words before opening each answer.
- Why is naive Fibonacci exponential?
Show answer
It recomputes the same subproblems many times, and the number of calls grows by a constant factor with each step.
- Name the two parts every recursive function needs.
Show answer
A base case and a recursive case that makes progress toward it.
- Why is
PowerO(log n) butPower(x, n/2) * Power(x, n/2)is O(n)?
Show answer
The second version makes two recursive calls per level, so the number of calls doubles at each of the log n levels, giving n calls.
- Why does merge sort use
<=instead of<when merging?
Show answer
To keep equal elements in their original order (stability).
- What is the time and space complexity of merge sort?
Show answer
O(n log n) time, O(n) extra space.
- When would you choose bubble sort over merge sort?
Show answer
Almost never in practice; it is only reasonable for tiny inputs or nearly sorted data with an early-exit check, and mainly useful for teaching.
- Why does
Binarycopycurwithstring(cur)?
Show answer
Because cur is reused and modified by later steps; without a copy, every stored result would change.
#Using the deep dive in the room
- Run each block as a loop: let students attempt the problem first, let the wall appear on its own, then introduce the concept and finish together. Resist explaining before they have felt the problem.
- Keep the time boxes honest. If a block runs over, move its "stretch" items to homework instead of cutting the recap card.
- Make students predict before running. Every code listing above is more valuable when someone has to guess the output first.
- The tests are part of the lesson, not an extra. Insist on a table-driven test for every function, including empty and boundary inputs.
#Putting it together: the tested package
All the functions from this guide live in one Go package, week4. Tests for Blocks A and B (the values from the plan, plus the three Fibonacci benchmarks):
package week4
import (
"math"
"testing"
)
func TestFib(t *testing.T) {
tests := []struct{ n, want int }{
{0, 0}, {1, 1}, {2, 1}, {10, 55}, {20, 6765}, {30, 832040},
{50, 12586269025}, {92, 7540113804746346429},
}
for _, tc := range tests {
if tc.n <= 30 { // the naive version is far too slow for 50 and 92
if got := FibNaive(tc.n); got != tc.want {
t.Errorf("FibNaive(%d) = %d, want %d", tc.n, got, tc.want)
}
}
if got := FibMemo(tc.n); got != tc.want {
t.Errorf("FibMemo(%d) = %d, want %d", tc.n, got, tc.want)
}
if got := FibIter(tc.n); got != tc.want {
t.Errorf("FibIter(%d) = %d, want %d", tc.n, got, tc.want)
}
}
}
func TestFactorial(t *testing.T) {
tests := []struct{ n, want int }{{0, 1}, {1, 1}, {2, 2}, {4, 24}, {5, 120}, {10, 3628800}}
for _, tc := range tests {
if got := Factorial(tc.n); got != tc.want {
t.Errorf("Factorial(%d) = %d, want %d", tc.n, got, tc.want)
}
}
}
func TestPower(t *testing.T) {
tests := []struct {
x float64
n int
want float64
}{
{2, 10, 1024}, {2, 0, 1}, {2, -2, 0.25}, {5, 1, 5}, {0, 5, 0}, {1.5, 2, 2.25}, {2, 30, 1073741824},
}
for _, tc := range tests {
if got := Power(tc.x, tc.n); got != tc.want {
t.Errorf("Power(%v, %d) = %v, want %v", tc.x, tc.n, got, tc.want)
}
if tc.n < 100 { // PowerLoop is only for small n
if got := PowerLoop(tc.x, tc.n); got != tc.want {
t.Errorf("PowerLoop(%v, %d) = %v, want %v", tc.x, tc.n, got, tc.want)
}
}
}
if got := Power(5, 0); got != 1 {
t.Errorf("Power(5, 0) = %v, want 1", got)
}
if got := Power(0, -1); !math.IsInf(got, 1) {
t.Errorf("Power(0, -1) = %v, want +Inf", got)
}
}
func TestReverse(t *testing.T) {
tests := []struct{ in, want string }{
{"", ""}, {"a", "a"}, {"abc", "cba"}, {"héllo", "olléh"}, {"abba", "abba"},
}
for _, tc := range tests {
if got := ReverseRecursive(tc.in); got != tc.want {
t.Errorf("ReverseRecursive(%q) = %q, want %q", tc.in, got, tc.want)
}
if got := ReverseRecursive2(tc.in); got != tc.want {
t.Errorf("ReverseRecursive2(%q) = %q, want %q", tc.in, got, tc.want)
}
}
}
func BenchmarkFibNaive30(b *testing.B) {
for i := 0; i < b.N; i++ {
FibNaive(30)
}
}
func BenchmarkFibMemo30(b *testing.B) {
for i := 0; i < b.N; i++ {
FibMemo(30)
}
}
func BenchmarkFibIter30(b *testing.B) {
for i := 0; i < b.N; i++ {
FibIter(30)
}
}The tests and benchmarks for Block C (the random test, the edge-case table, stability, quick sort, Binary, DigitSumRec, ToBinary, CountInversions and every benchmark) are in code/week4/blockc_test.go. Run everything with go test -v ./....
#Recap
| Idea | One sentence |
|---|---|
Input size n | Cost is described as a function of how big the input is. |
| Big O | How the number of steps grows as n grows; drop constants and small terms; usually worst case. |
| Repeated work | FibNaive re-solves the same subproblems; calls grow exponentially (~1.6× per step). |
| Memoization (top-down) | Write each answer in a map the first time; reuse it. O(n) time, O(n) space. |
| Loop (bottom-up) | Keep only the last two values. O(n) time, O(1) space. |
| Call stack | One frame per active call; push on call, pop on return. |
| Base case + recursive case | Stop on the smallest input; otherwise call yourself on a smaller input. |
| Missing base case | Stack overflow after about 1 GB of stack: fatal, not recoverable. |
| Halving | Power shrinks n by half each call: O(log n). Store the half-result once. |
| Hidden costs | Copying strings in each call makes reverse O(n²); swapping indices makes it O(n). |
| Recursion vs loop | Recursion fits self-similar problems with small depth; loops avoid stack growth. |
| Bubble sort | Compare neighbours, swap, repeat: O(n²) time, in place; O(n) if already sorted. |
| Divide and conquer | Split, solve each half recursively, combine the answers. |
| Merge sort | Sort halves, then merge with two pointers: O(n log n) time, O(n) extra space, stable. |
| Quick sort | Partition around a pivot, sort both sides: average O(n log n), in place, worst O(n²), not stable. |
| Backtracking | Choose, explore, undo (and copy any result you want to keep). |
| Testing | Compare against the standard library on many seeded random inputs, plus a table of edge cases. |