Blog

Runs times cost: the ideas I'm keeping from my data structures midterm

What I learned studying for my data structures and algorithms midterm: how I work out the cost of code now, how recurrences, sorting and trees fit together, and a routine for writing recursive methods in Java.

I just wrote my data structures and algorithms midterm, and what I want to talk about isn’t the midterm itself. It’s how I read code now compared to how I read it before studying for it. We covered this material in Java, and initially, loops, recurrences, sorting and trees looked like separate things to learn. Most of it started to come together when I had two questions I could ask regardless of what code I was looking at.

Idea one: runs times cost

The first question is: how many times does this line run, and how much does it cost each time? If the cost is the same every time, I multiply the two. If the cost changes, I add up the individual runs. Then I put the lines together.

For example, here’s how I read a few loop headers. The counts assume n is positive, and the growth column is for a constant-time loop body.

Header Passes Growth
int i = 0; i < n; i++ n O(n)
int i = 0; i < 4; i++ 4 O(1)
long j = 1; j < n; j = j * 2 about log₂ n O(log n)
int j = n; j > 1; j = j / 2 about log₂ n O(log n)

Now, what makes those last two logarithmic? With n = 16, the doubling loop visits 1, 2, 4 and 8. It doesn’t visit every number between 1 and 16. It takes four doublings to get there. If I double n, it needs one more pass. That’s different from adding one each time, where doubling the range doubles the work. I use a long counter in the doubling example so it doesn’t overflow when n is a large positive int.

When loops are side by side, I add their costs. When one is inside the other, I check whether the inner loop does the same work each time. Here it does, so I can multiply:

for (int i = 0; i < n; i++) {             // n passes
    for (long j = 1; j < n; j *= 2) {     // about log n passes
        total++;                         // O(1)
    }
}
for (int k = 0; k < n; k++) {             // n passes
    total--;                             // O(1)
}

So that’s n × log₂ n work for the nested part, plus n for the loop after it. I keep the term that grows faster, which gives me O(n log n). The same idea applies to n² + n: the n² term dominates. But n × n² is n³; that’s a multiplication, not two separate pieces of work to add.

One thing I remind myself of: the value a line produces isn’t the amount of work it did. return (long) n * n; is still O(1) for an int, even though the result is n squared. And if a loop’s first check is false, the body doesn’t run at all. You still paid for the check.

Idea two: what happens when n doubles?

The second question is: if I double the input, what happens to the work? This isn’t the formal definition of Big-O, which gives an upper bound on growth. It’s a way for me to get a feel for the difference between, for example, linear work and quadratic work. For 3n² and n², doubling n quadruples the work in both cases. The factor of three matters if I’m timing the code, but it doesn’t change the growth rate.

Work proportional to When n doubles, the representative function…
1 stays the same
log₂ n goes up by 1
n doubles
n log₂ n a bit more than doubles
n² quadruples
2ⁿ squares

The one I had to work through was n log n. For n = 8, n × log₂ n is 24; for n = 16, it’s 64. That’s twice 24, plus another 16. Another way I look at it is to divide by n. For n that leaves 1 every time. For n log₂ n, it leaves log₂ n, which goes up by 1 every time the input doubles.

Method calls: picture the body at the call site

Now, if the line is a method call, what does one run cost? I picture the method body at the call site, with the actual argument filled in. If printRow(k) prints k items and each item takes constant work to print, then printRow(5) is O(1) and printRow(n) is O(n). Of course, a method could also read an array or other state whose size changes. The point is to look at what the method actually works on.

For a changing argument, I write down three things: one call, arguments passed, and all calls added.

for (int i = 0; i < n; i++) {
    printRow(i + 1);
}

One call does work proportional to its argument. The arguments are 1, 2, 3, up to n. So I add 1 + 2 + … + n, which is n(n + 1) / 2, giving O(n²). This is the case where I can’t just say the inner work is the same for every pass. The last row is doing a lot more work than the first one.

I still rebuild the sum rather than memorising it. Write it forwards, then backwards underneath. Each column adds to n + 1, there are n columns, and I’ve counted everything twice, so I divide by two. If the sum starts at 0 and ends at n − 1, the same process gives n(n − 1) / 2. That’s why I check the first and last terms before reaching for a formula.

Recurrences: input inside, work outside

For recursion, I want to know what smaller calls actually happen, and what work the current call does outside of them. For example:

public static long halve(int n) {
    if (n <= 1) {
        return 1;
    }
    long steps = 0;
    for (int i = 0; i < n; i++) {
        steps++;
    }
    return steps + halve(n / 2);
}

If T(n) counts what this method returns, the base case is 1, and for n > 1 it’s T(⌊n/2⌋) + n. Java’s integer division rounds down here because n is positive. This isn’t an exact count of every operation in the program. It counts the loop increments plus the base-case 1, which is enough to see the growth.

What made this click for me was saying out loud what n/2 actually means. It’s the size of an input. T(n/2) is the work at that size. It’s not T(n)/2. For example, if the work is quadratic, going from 8 to 4 takes you from 64 to 16, not from 64 to 32.

A few checks I use when I write one down:

  • Count the calls that run. Two half-size calls give 2T(n/2). Two branches that each have a call don’t give you two calls if only one branch runs.
  • Use the argument the call receives. count(k - 1) with k = 5 gets 4, so that call costs T(4).
  • Count the work outside the recursive calls too. That includes loops and calls to other methods.
  • Look at the base case itself. Stopping the recursion doesn’t automatically make the base case constant-time. If it scans an array of the original size, the scan still depends on that size.

Solving a recurrence from a table

I like starting at T(1) and working my way up. But before looking at the results column, I look at the inputs. If the recurrence uses n/2, I can work with inputs that double: 1, 2, 4, 8, 16. I look at ratios or divide T(n) by n. If it uses n − 1, I write consecutive inputs and look at the differences instead.

Change in T(n) when n goes up by 1 Growth pattern to check
Stays the same linear
Grows by a fixed amount, as in 3, 5, 7, 9 quadratic
Doubles, as in 2, 4, 8, 16 exponential, with base 2

Here’s why I care about the input column. The halve example gives 1, 3, 7, 15, 31 at inputs 1, 2, 4, 8, 16. Dividing by n gives numbers that approach 2. And if I expand the recurrence, the work is n + n/2 + n/4 + …, which comes to less than 2n. So it’s linear. But T(n) = 2T(n − 1) + 1 gives those same values at inputs 1, 2, 3, 4, 5. Here I’m doubling the previous result and adding one for every single step in n, so the work is O(2ⁿ). Same results in the table, but they correspond to different inputs.

With 2T(n/2) + n and a base of 1, the results at inputs 1, 2, 4, 8, 16 are 1, 4, 12, 32, 80. When I divide by n, I get 1, 2, 3, 4, 5, which suggests n log n. The table helps me see what to check. It isn’t the proof by itself, which is where the sorting example helps.

Sorting: look at the split

Quicksort goes through the values to partition them around a pivot, then sorts the two groups. If the groups are roughly even, the recurrence looks like 2T(n/2) + n and the work is O(n log n). Now, what happens if one group is empty every time? The pivot is done, but there’s still a group of n − 1 to sort. That’s T(n − 1) + n, which is the triangle sum again and gives O(n²). With randomly chosen pivots and distinct keys, the expected cost is O(n log n).

Standard mergesort doesn’t depend on the pivot because there isn’t one. It splits in the middle and does the work of merging afterward. Say you have eight values. There’s a level that handles 4 + 4, one that handles 2 + 2 + 2 + 2, and one that handles all 8. That’s eight values’ worth of work at each of three merge levels, plus the base cases. That is where the n and the log n come from.

A good best case doesn’t always mean the code stops early. The balanced quicksort example still does the partitioning; it just ends up with smaller groups to work on. For a plain scan that finds the largest value in an unsorted array, on the other hand, even finding the largest one first doesn’t save you a pass. You still have to look at the rest to know it was the largest.

Trees: reaching the spot and changing it

For trees, and for data structures in general, I’ve been asking what it costs to get to the spot I want and what it costs to make the change once I’m there. Those can be two very different numbers.

Structure Reaching the insertion spot Changing it
Sorted array binary search can find the rank in O(log n) shift up to n values, O(n)
Linked list with only a head reference walk up to n links, O(n) relink pointers once you have the right references, O(1)
Ordinary BST follow one path from the root, O(height) attach the new leaf, O(1)

In a binary search tree, the part I can’t ignore is the shape. These are the terms my course uses; what we called full is also commonly called perfect. We counted height in levels, so one node has height 1.

Course term Levels above the last Last level
Full all filled filled
Complete all filled filled from the left, no gaps
Minimum-level all filled may have gaps

Under those definitions, full implies complete, and complete implies minimum-level. I check the rows above the last one first, then look at what the last row is doing. A tree with all the upper levels filled has height on the order of log n, so search and insert are O(log n).

Now compare that with inserting 10, 20, 30, 40 and 50 into an empty, unbalanced BST. Every new value goes to the right of all the previous ones. To build it, I do 0 + 1 + 2 + 3 + 4 comparisons. That’s n(n − 1) / 2 in general, which is O(n²). But one search isn’t O(n²): it follows one path and can take up to O(n). And not every path is long, either. If I insert 5 into that same tree, it’s one comparison before I know it belongs to the left of the root.

Writing recursive methods: base, shrink, combine

When I’m writing a recursive method rather than reading one, I go in this order:

  1. Base: At what input can I return an answer without making another call?
  2. Shrink: How does this call get closer to that case, and will it actually reach it?
  3. Combine: If I trust the smaller call to do its job, what does this one add?

For that last question I like writing out an example. Say I want to add the digits of a non-negative number. sumDigits(472) is 4 + 7 + 2. Well, the 4 + 7 part is just sumDigits(47). The part I still have to add is 2, which I get from n % 10, and I get 47 from n / 10:

public static int sumDigits(int n) {
    if (n < 10) {
        return n;
    }
    return n % 10 + sumDigits(n / 10);
}

Then I trace the checks with actual numbers: 472 < 10? No. 47 < 10? No. 4 < 10? Yes. I also check the boundary. If I wrote n <= 10 instead, sumDigits(10) would give me 10 when I wanted 1.

With a tree, smaller doesn’t mean dividing an integer. It means going to a subtree with fewer nodes. The empty tree gives me a base case, and what I do at the current node depends on the answer I want:

Method returns What happens at this node
number of nodes add 1 to the two subtree counts
total of the values add current.value to the two subtree sums
height in levels add 1 to the larger of the two heights
number of leaves return 1 if this is a leaf; otherwise add the two counts
public static int countLeaves(Node current) {
    if (current == null) {
        return 0;
    }
    if (current.left == null && current.right == null) {
        return 1;
    }
    return countLeaves(current.left) + countLeaves(current.right);
}

The order there matters. I check for null before reading current.left, because even an ordinary node with one child is going to make a call on its empty side.

My cheat sheet

Situation Cost
T(n/2) + 1 (binary search) O(log n)
T(n/2) + n O(n)
2T(n/2) + n (standard mergesort, balanced quicksort splits) O(n log n)
T(n − 1) + n (quicksort worst case) O(n²)
2T(n − 1) + 1 O(2ⁿ)
Find the largest value by scanning an unsorted array O(n)
Insert into a sorted array O(1) if I can append into a free slot; O(n) worst case
Search or insert in a minimum-level BST O(log n)
Search a BST that has become a vine O(n) worst case
Build an unbalanced BST by inserting distinct sorted values O(n²)

Where this leaves me

The biggest change for me is that I don’t have to guess from what the code looks like. I can point to the loop that does the work, the path a value actually takes through a tree, or the smaller problem inside a recursive method. And if I can’t explain where the cost came from, that’s when I write down the steps with a small input and see what actually runs. That’s the habit I’m taking into the rest of the course.