Skip to content

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.

13 min read0/6 questions

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 shapeWhat it suggests
Array of numbersHashing, sorting, prefix sums, two pointers, windows
Sorted arrayBinary search, two pointers from both ends
StringCharacter counts, windows, two pointers for palindromes
String of brackets or operatorsA stack for nesting and matching
Matrix / grid of cellsA 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 treeRecursion on left and right subtrees, or BFS by level
head of a linked listPointer moves: fast and slow, reversing, a dummy node
A stream, or a class with methodsDesign: 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.

Quick check
'Given an m x n map of '1' (land) and '0' (water), count the islands.' What is the input really?
Need a nudge? A hint rules out a wrong answer.

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 true at the first duplicate, false at 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 pairs0/5 matched

Match the output form to what it tells you.

Choose an item, then its match on the other side.
Quick check
A problem asks you to return all permutations of up to 8 distinct numbers. Can any algorithm be O(n²)?
Need a nudge? A hint rules out a wrong answer.

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:

  1. A small normal case you can solve by hand in under a minute. This is the one you will trace your code on.
  2. 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.
  3. 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.

Predict the outputPython

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]))
Need a nudge? Hints walk you through it.

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.

Drawing '([]{})' and what you need to remember
(
0
↑i
[
1
]
2
{
3
}
4
)
5
open = (

Draw the characters with indices. At index 0 we see (. Write it down as *still open*.

1/5
Put it in order5 steps

Put the example routine in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]]. Output: an integer. What is the most likely question and first step?
Need a nudge? A hint rules out a wrong answer.

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.

ChallengeEasy

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^4
  • s contains only the characters ()[]{}.
  • An empty string counts as valid.
def is_valid(s: str) -> bool: # Push opening brackets; each closing bracket must match the latest one. pass
Key terms
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.