Mental model
An algorithm is a finite sequence of unambiguous steps that turns every valid input into a correct output. A data structure is a way of arranging data so that the operations an algorithm needs are cheap. Both only make sense relative to a problem, and a problem is a contract with three parts:
- Input: what you are given, its types, its size, and every property you may rely on (sorted? distinct? non-empty? within some range?).
- Output: exactly what must be returned for each input, including ties and the "nothing found" case.
- Constraints: how large the input can be and how much time and memory you may use.
Writing the contract first is not bureaucracy. Each line either rules out a bug or rules out an approach. "Values are sorted" makes binary search possible. "There may be duplicates" forces you to say which match you return. "n can be a million" rules out comparing every pair.
A contract for linear search
The lab above runs the smallest complete example: find a target in an array. A precise contract:
- Input: an array of integers (any order, duplicates allowed, possibly empty) and a target integer.
- Output: the smallest index
iwithvalues[i] == target, or-1if there is none. - Constraints: only equality tests on elements; O(1) extra memory.
Every phrase does work. "Smallest" settles duplicates: the Duplicates: first match preset stops
at index 2 and never looks at the second 19. "Possibly empty" is a real input, not an error: the
Empty array preset returns -1 after one bounds check and no comparison. "Any order" is why no
faster method exists: without ordering, any element you skip could be the target. The Not found
preset shows the price, n comparisons.
A different, equally valid contract ("return any matching index", or "return a boolean", or "throw if absent") would change the implementation and the tests. That is why the contract comes first.
Questions to ask about any input
| Question | Why it matters |
|---|---|
Can it be empty? Can it be null/None? |
Loops that read values[0] or compute n - 1 break on empty input. |
| Is it sorted? By what? | Enables binary search, two pointers and merging; otherwise you may need to sort first (O(n log n)). |
| Can values repeat? | Decides which match you return and whether a set loses information. |
| What range do values take? | Sums and products can overflow fixed-width integers; small ranges allow counting arrays. |
| How large can n get? | Decides which growth rate is acceptable (next section). |
| May I modify the input? | Sorting in place is cheaper than sorting a copy, but the caller may not expect it. |
| Is the input given all at once? | A stream you see once rules out sorting and random access. |
From constraints to a target complexity
Once you know the largest n, you can rule out approaches before writing them. The table below is a rule of thumb, not a guarantee: it assumes roughly 10⁷ to 10⁸ simple operations per second in compiled C#, Java or C++ (often ten or more times fewer in CPython) and a time budget of about a second.
| Largest n | Growth rates that usually fit | Typical shape |
|---|---|---|
| ≤ 10 | O(n!), O(n · n!) | try every ordering |
| ≤ 20–25 | O(2ⁿ), O(n · 2ⁿ) | try every subset |
| ≤ a few hundred | O(n³) | three nested loops |
| ≤ about 10⁴ | O(n²) | every pair |
| ≤ about 10⁶ | O(n log n) | sort, then scan; heap; balanced tree |
| ≥ 10⁷ | O(n), O(log n), O(1) | one pass, hashing, binary search |
The exact count matters at the boundaries; the Big O explorer draws these curves side by side, and module M03 shows how to count. The useful habit is the direction of reasoning: constraints → acceptable growth → candidate techniques.
Worked example: has any badge been scanned twice?
The problem Has any badge been scanned twice? gives you a log of integers and asks whether any value appears more than once.
Contract. Input: an array of integers, possibly empty, any order. Output: true if some value
occurs at least twice, else false. An empty or one-element log returns false.
Brute force. Compare every pair:
Pseudocode
for i from 0 to n - 1:
for j from i + 1 to n - 1:
if values[i] == values[j]: return true
return false
In the worst case (no duplicate) this makes n(n − 1)/2 comparisons: Θ(n²) time, O(1) extra space. It is obviously correct, which makes it valuable even when it is too slow: it is the reference you test faster versions against. Every algorithm in this lab is checked that way, against a simple or built-in reference on random inputs.
Decompose and look for structure. The question "have I seen this value before?" is asked once per element. Two ways to make that question cheap:
- Sort, then compare neighbours. After sorting, equal values are adjacent, so one pass of n − 1 neighbour comparisons answers the question. Cost: O(n log n) for the sort, plus O(n). It either modifies the input or needs a copy.
- Remember what you have seen in a hash set. For each value: if it is in the set, return
true; otherwise add it. n expected-O(1) set operations: O(n) expected time, O(n) extra space.
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| All pairs | Θ(n²) worst case | O(1) | the test oracle |
| Sort + neighbours | O(n log n) | O(1) to O(n), depending on the sort and whether you copy | changes order unless you copy |
| Hash set | O(n) expected | O(n) | worst case degrades if many values collide |
Choose with the constraints. With n ≤ 1,000 all three are fine and the simplest correct one wins. With n = 10⁶, the pairwise version needs about 5 × 10¹¹ comparisons and is out; the other two are both reasonable, and the choice comes down to whether memory or input order matters more. This is what "choosing a data structure" means in practice: the step "have I seen x?" needs fast membership, and a set is the structure built for that. The hashing for lookup pattern collects more problems with the same shape, and the two readings that add up to a target problem uses a map instead of a set for the same reason.
Pseudocode
Pseudocode is a plan, not a program. Good pseudocode states loop bounds exactly (0 to n - 1,
inclusive or exclusive), names the data structure (seen = empty hash set), and leaves out
language noise such as type declarations. If you cannot write the loop bounds in pseudocode, the
off-by-one bug will appear in the real code too. The listings below the lab show how one plan
becomes four programs with the same structure.
Language notes
The same contract can mean different things in different languages:
- Integer width. C#
intand Javaintare 32-bit and wrap around silently on overflow (C# throwsOverflowExceptiononly in acheckedcontext). C++ signed overflow is undefined behaviour, so the compiler may assume it never happens. Pythoninthas unlimited precision and never overflows, but grows slower as numbers get larger. A constraint such as "values up to 10⁹, n up to 10⁵" means a sum can reach 10¹⁴: uselong(C#, Java) orstd::int64_t(C++). - Missing input. C#, Java and Python have a null reference (
null,None); decide whether the contract allows it. A C++std::vectororstd::spancannot be null, only empty. - "Not found" conventions differ.
List<T>.IndexOf(C#) andList.indexOf(Java) return-1. Python'slist.indexraisesValueErrorinstead (whilestr.findreturns-1). C++std::findreturns the end iterator. Code that ports a contract between languages must translate this, not copy it. - Equality. Linear search needs only an equality test, but what
==means depends on the type: value equality for numbers and strings in Python and for C# strings, reference identity for Java objects compared with==(useequals). Module M04 covers this in detail.
Common mistakes
- Solving the example instead of the problem. Checking only the sample input misses the empty, the single-element and the all-equal cases.
- Unstated assumptions. Relying on sorted input, distinct values or a non-empty array without the contract saying so.
- Ignoring the size constraint until the solution times out, or optimising a problem where n ≤ 100 and the brute force was fine.
- Forgetting the cost of a hidden step, such as sorting before a binary search, or copying an array to avoid modifying it.
- Ambiguous output. "Return the index" without saying which one, or what to do when there is none.
Edge cases
A checklist that catches most contract gaps:
- empty input, one element, two elements;
- all elements equal, all distinct;
- the answer at the first position, at the last position, or absent;
- the smallest and largest allowed values (overflow, negative numbers);
- already sorted and reverse sorted input.
The next lesson turns this list into a habit and adds the tool that proves a loop correct: the loop invariant.
Worked practice
1. Write a precise contract for "find the largest value in an array".
Input: an array of integers, any order, duplicates allowed. The empty case must be decided: either
the contract requires n ≥ 1, or it says what to return (an error, a sentinel, or "no value", such
as an optional). Output: a value m that occurs in the array with m ≥ x for every element x.
Note that the output is a value, not an index; with duplicates, the index would need its own rule.
2. n ≤ 200,000. Is an all-pairs O(n²) solution acceptable?
n² = 4 × 10¹⁰ elementary steps, and even n(n − 1)/2 is 2 × 10¹⁰: far over the rule-of-thumb budget of about 10⁸ per second. Look for O(n log n) or O(n).
3. In the duplicate problem, when is "sort + neighbours" the better choice than a hash set?
When extra memory is tight and the input may be reordered (an in-place sort needs O(1) to O(log n) extra space, a hash set needs O(n)), or when you also need the values in order afterwards. The hash set wins when the input order must be preserved and memory is available.
4. The contract says "return the index of the target". Name two questions you must ask.
Which index if the target occurs several times (first, last, any)? What to return if it is absent
(-1, an exception, an insertion point)? Also: can the array be empty, and is it sorted?
Summary
- A problem is a contract: input properties, exact output, size and resource constraints.
- The largest n tells you which growth rates are worth trying before you write code.
- Brute force first: it is correct, it is your test oracle, and its cost tells you how much better you need to be.
- Decompose the problem into steps; the operations those steps need choose the data structure.
- Integer width, null handling and "not found" conventions differ between C#, Python, Java and C++; a contract must say which one it means.