Lesson 2 of 27Read before you code
Inputs, Outputs, and Examples
Read the shape of the input and output for clues, build your own small and weird examples, and draw them.
You can now restate what a problem asks in one sentence. Before you study its wording or its constraints, look at something even more basic: what kind of thing you are handed and what kind of thing you must hand back. A matrix of 0s and 1s, a string of brackets, a list of pairs. Those shapes narrow the possible patterns a lot. Then you make your own examples, because the ones in the prompt are chosen to be friendly and the hidden tests are not.
The shape of the input
Each input shape comes with a set of natural moves. Seeing the shape should bring them to mind.
| Input shape | What it suggests |
|---|---|
| Array of numbers | Hashing, sorting, prefix sums, two pointers, windows |
| Sorted array | Binary search, two pointers from both ends |
| String | Character counts, windows, two pointers for palindromes |
| String of brackets or operators | A stack for nesting and matching |
| Matrix / grid of cells | A graph: each cell is a node with 4 (or 8) neighbours. DFS, BFS, or a 2D DP table |
List of pairs [a, b] meaning "a depends on b" or "a connects to b" | An edge list: build an adjacency list, then BFS, DFS, or topological sort |
List of [start, end] | Intervals: sort by start, then sweep |
root of a tree | Recursion on left and right subtrees, or BFS by level |
head of a linked list | Pointer moves: fast and slow, reversing, a dummy node |
| A stream, or a class with methods | Design: pick a structure that makes each method cheap |
A grid is the shape people most often fail to recognise. "Count the islands" does not say "graph" anywhere, but a grid is a graph. Once you see that, number of islands is "count connected components", and you already know how to do that.
m x n map of '1' (land) and '0' (water), count the islands.' What is the input really?The shape of the output
The output form is just as telling. Read it slowly.
- An index or indices. Positions matter, so sorting is risky (it moves things). Keep the index alongside the value, or use a map from value to index.
- A value. Positions do not matter, so sorting is allowed.
- A boolean. You can often stop early: return
trueat the first duplicate,falseat the first mismatch. - A count or a length. You do not have to build the things you count. That often means DP or a formula rather than listing.
- A minimum or maximum. Greedy, DP, or binary search on the answer (if "can it be done with x?" is easy to check).
- A list of all solutions. Backtracking. The output size is a lower bound on the time: if there are 2ⁿ subsets, no algorithm can list them in less than 2ⁿ steps.
- Nothing, "modify in place". Your function changes the input and usually returns
None. Building a new list and returning it fails the tests.
Match the output form to what it tells you.
Make your own examples
The examples in the prompt are there to explain, not to test. They are usually small, tidy, and avoid every awkward case. Make three of your own:
- A small normal case you can solve by hand in under a minute. This is the one you will trace your code on.
- A large case in your head ("10^5 values all the same", "a 200 by 200 grid of land"). Not to run, but to check your complexity and recursion depth.
- A weird case: empty, one element, all equal, already sorted, reverse sorted, negatives, no valid answer.
Writing your own example is also how you check you understood the problem. If you cannot work out the expected answer by hand, you do not understand the rules yet.
A quick solution to Best Time to Buy and Sell Stock. What does it print on your own weird example?
def max_profit(prices): return max(prices) - min(prices) print(max_profit([5, 3, 1]))
Draw it
For arrays and strings, draw the cells with their indices underneath. For grids, draw the grid. For graphs, draw circles and arrows. A drawing makes patterns visible that a list of numbers hides, like "the answer is always a range" or "these cells form a ring".
Here is the habit on Valid Parentheses. Draw the string with indices, then walk it and write down what you need to remember at each step.
Draw the characters with indices. At index 0 we see (. Write it down as *still open*.
Put the example routine in order.
- Tap the steps below in the right order.
n = 5 and edges = [[0, 1], [1, 2], [3, 4]]. Output: an integer. What is the most likely question and first step?Practice
Before you code, write your own three examples for this problem: one normal, one with the wrong closer, and one with an opener left over.
Valid Parentheses
Given a string s made only of the characters ()[]{}, return true if every bracket is closed by the same type of bracket, in the right order. An opening bracket must be closed before any bracket opened earlier is closed.
"()[]{}" → true
"{[]}" → true
"([)]" → false (] closes while ( is still the latest open)Constraints
0 <= s.length <= 10^4scontains only the characters()[]{}.- An empty string counts as valid.
- input shape
- The form of the data you are given (array, grid, edge list, intervals, tree). Each shape suggests a set of natural moves.
- grid graph
- A matrix where each cell is a node with up to four neighbours. Islands and flood fill are graph problems.
- output lower bound
- If you must return k items, the time is at least k. Listing 2ⁿ subsets takes at least 2ⁿ steps.
- weird case
- A hand-made example the prompt avoids: empty, one element, all equal, no valid answer.
- in place
- Change the input directly and usually return nothing, instead of building a new result.