Card 08/ 08
Recap: Solving an Unseen Problem
Clarify, work examples, cost the brute force, find the bottleneck, write and trace, with the limits setting the budget.
Solving an unseen problem means taking the same six steps in the same order, so the work starts from questions rather than from code.
- Clarify the input, the output and the limits: the size, the range and sign of the values, duplicates, the empty input, and the form of the answer.
- Work two examples by hand, one of them an edge case, and keep their answers as tests.
- State the brute force and its cost.
- Find the bottleneck, the part that dominates the cost, and choose an approach that removes it within the budget.
- Write the code.
- Trace the examples through it, and go back to step 4 or 5 when an answer disagrees.
The limits set the budget. At roughly 10⁸ simple steps a second, the largest input decides the slowest complexity that fits, and every row is a rough guide: a solution at the edge of one is a reason to choose the faster complexity, not to measure.
| Largest n | Complexity that fits |
|---|---|
| 10 | O(n!) |
| 20 | O(2ⁿ) |
| 500 | O(n³) |
| 5,000 | O(n²) |
| 10⁶ | O(n log n) or O(n) |
| Larger | O(log n) or O(1) |
Two traps undo the sequence. Skipping step 1 lets an unchosen assumption into the code, such as a maximum that starts at 0 on readings that can be negative, or an empty input nobody decided how to answer. Skipping step 3 on small limits hides the fact that the brute force already fits: at 20 items or fewer, trying every subset is often the answer. Most later topics in this subject are step 4's moves, each removing one kind of bottleneck, and the hash map, which turns a search inside a loop into one lookup, is the first of them.
← → move through sections and cards