Sub topic 15
Choosing the Right Level of Detail
This chapter assumes you have worked through the earlier chapters. You should be able to read pseudocode, trace a loop with a state table, and state a running time in Big-O notation. You should also know Euclid's algorithm well, because it appears again here as a reference point.
Every description of an algorithm leaves something out. Plain language leaves out variable names. Pseudocode leaves out types and memory layout. Python leaves out the machine instructions. So the real question is which details you leave out, and whether the reader can still do their job without them.
One Algorithm, Several Levels
Here is Euclid's algorithm written at four levels of detail, from coarsest to finest.
| Level | Description of Euclid's algorithm | Who it serves |
|---|---|---|
| One sentence | Repeatedly replace the pair (a, b) with (b, a mod b) until b is 0; then a is the GCD. | Someone who already knows what GCD and mod mean and wants the idea |
| Structured natural language | The numbered four-step version from the earlier chapter, with input and output stated | A reader checking the logic or tracing by hand |
| Pseudocode | `while b != 0 do r <- a mod b; a <- b; b <- r` with pre- and postconditions | A programmer about to implement it in any language |
| Program | `a, b = b, a % b` inside a Python `while` loop | A computer, and anyone maintaining that code |
All four describe the same algorithm. The one-sentence version is complete for an expert, because every phrase in it names an operation the expert can carry out without making a decision. For a reader who has never met "mod", the same sentence is not a usable algorithm at all.
What Counts as a Primitive Step
A primitive step is an operation the description treats as a single unit that needs no further explanation. Choosing your level of detail mostly means choosing your primitives.
Ask three questions about each step you write:
- Can the reader perform it without asking you anything?
- Does it hide a decision that affects correctness, such as how ties are broken, what happens on empty input, or whether a bound is inclusive?
- Does it hide work that affects cost, such as a step that looks constant-time but takes linear time?
If the first answer is no, or the second or third is yes, the step needs to be broken into smaller steps. Otherwise leave it alone. Breaking it down further adds length without telling the reader anything.
Stepwise Refinement
Stepwise refinement is a way to move between levels on purpose. You write the algorithm at a coarse level, then replace each step that fails the three questions with a more detailed sub-description. You stop when every remaining step is primitive for your audience.
A worked refinement
Problem: given a list, return a new list with duplicates removed, keeping the first occurrence of each value in its original order.
Level 1, the idea:
Walk through the list once, keeping each value the first time you see it.Level 2, structured steps. Refining "the first time you see it" forces us to say how we remember what we have seen:
Input: a list of hashable values, items.
Output: a list containing each distinct value of items once, in order of first appearance.
1. Start with an empty collection seen and an empty list result.
2. For each value x in items, in order:
a. If x is not in seen, add x to seen and append x to result.
3. Return result.Level 3, a program:
def dedupe(items):
# Precondition: every element of items is hashable
# Postcondition: returns distinct elements in order of first appearance
seen = set()
result = []
for x in items:
if x not in seen:
seen.add(x)
result.append(x)
return result
print(dedupe([3, 1, 3, 2, 1])) # [3, 1, 2]Level 1 was enough to explain the idea. It was not enough to judge cost, and that is where an under-detailed description can mislead.
The Hidden-Cost Trap
The step "if x is not in seen" looks like a single primitive operation. Its cost depends on what seen is. Compare:
def dedupe_slow(items):
seen = [] # a list, not a set
result = []
for x in items:
if x not in seen: # scans seen: up to len(seen) comparisons
seen.append(x)
result.append(x)
return result
print(dedupe_slow([3, 1, 3, 2, 1])) # [3, 1, 2]Both programs match the Level 2 description, and both are correct. But membership in a Python list takes O(k) comparisons for a list of length k, so dedupe_slow does up to 0 + 1 + ... + (n − 1) comparisons, which is O(n²). The set version does an expected O(1) check per element, so it runs in O(n) expected time.
If your description exists to support a cost claim, the data structure behind "seen" is a decision that changes the answer, and the description has to name it. If the description only explains the idea, you can leave it out.
Matching Detail to Purpose
The same reader may need different levels for different jobs. Decide what the description is for, then keep exactly the details that job depends on.
| Purpose | Must include | Safe to omit |
|---|---|---|
| Explaining the idea | The key insight and the overall shape (one pass, divide in half, repeat until) | Variable names, edge cases, data structures |
| Hand tracing | Every variable that changes, and the order of updates | Language syntax, types |
| Correctness argument | Preconditions, postconditions, loop structure, the invariant | Micro-optimisations, I/O |
| Termination argument | The quantity that decreases and its lower bound | Most of the loop body |
| Cost analysis | Every loop bound and the true cost of each step inside loops | Constant factors, naming |
| Implementation | Edge cases, tie-breaking, inclusive/exclusive bounds, data structures | Proof details |
Look at Euclid's algorithm again. For a termination argument, the one-sentence level is almost enough: you only need to know that b is replaced by a mod b, which is a non-negative integer smaller than b. For a hand trace you need the pseudocode, because the order of the updates matters. Writing a <- b before computing a mod b would give a different and wrong algorithm.
Common Errors
| Error | Symptom | Fix |
|---|---|---|
| Too coarse for the reader | Reader asks "how do I do step 3?" | Refine that step into sub-steps |
| Hidden decision | Two people implement it and get different outputs on ties or empty input | State the rule explicitly in the step |
| Hidden cost | Stated O(n), measured behaviour grows quadratically | Name the data structure or expand the step |
| Too fine for the reader | The idea is buried under index arithmetic | Lift repeated detail into a named sub-step |
| Mixed levels | One step says "sort it", the next spells out swapping two variables | Refine all steps to roughly the same depth |
| Language leakage | Pseudocode depends on Python-only behaviour such as negative indexing | Replace with a language-neutral operation |
The mixed-levels error is easy to miss. A reader takes the level of detail as a signal of what matters. If one trivial step is spelled out in full while a hard step is a single phrase, the reader's attention goes to the wrong place.
A Practical Checklist
Before you finish any algorithm description:
- Name the reader and the purpose in one sentence.
- List the primitive operations you are assuming that reader knows.
- Check every step against the three questions: performable, no hidden decision, no hidden cost.
- Make sure all steps sit at a similar depth.
- Check that the input, output, and preconditions are stated at the top, whatever the level.
The last item holds at every level. Even a one-sentence description should say what goes in and what comes out, because without that it describes no particular problem.
Exercise
A teammate writes "Binary search: repeatedly look at the middle element and discard the half that cannot contain the target." You need to hand this to a junior developer who will implement it. Name two hidden decisions that must be made explicit, and say why each matters.
Show answer
First, the bounds convention: whether the search range is inclusive (low..high) or half-open (low..high-1), and how "middle" is computed, for example (low + high) // 2. If this is inconsistent, the code can loop forever or skip elements. Second, the stopping rule and the not-found result: when the range is empty and what is returned, such as -1. Other acceptable answers include the precondition that the list must be sorted, and which index to return when the target appears more than once.
Exercise
A description says "For each word in the document, if the word is not already in the output list, append it." The author claims O(n) time for n words. Is the claim justified by the description? What single change to the description would make it justified?
Show answer
It is not justified. "Not already in the output list" is a membership test on a list, which costs up to the list's length, so the worst case is O(n^2). Saying that seen words are tracked in a hash set, with an expected O(1) membership test, supports an expected O(n) claim.
Exercise
Rewrite Euclid's algorithm at the right level for a reader whose only job is to argue that it terminates. Keep only what that argument needs.
Show answer
"Input: integers a >= 0, b >= 0, not both zero. While b is not 0, replace (a, b) with (b, a mod b); then return a." This is enough because a mod b is a non-negative integer strictly less than b, so b strictly decreases and is bounded below by 0, and the loop must stop. Temporary variables and update order are not needed for this argument.