Fanpilot

Worked problems

2 min read

Each lesson takes one problem from the slow solution to the fast one, in Python, and shows why the fast one is correct. Every lesson ends by changing one rule of the problem and asking whether the solution still works.

How each lesson works

Every lesson follows the same steps, so you can compare techniques side by side:

  1. The problem, with examples.
  2. The slow solution that obviously works, and what makes it slow.
  3. The key observation that removes the slow part, and what it depends on.
  4. The fast solution, with a step-by-step trace.
  5. Why it works, in a form you could check yourself.
  6. Cost, edge cases, and where it breaks, including a small input that defeats it.

A collapsed section at the end has related problems, random tests against the slow solution, and an exercise to rebuild the solution from memory.

Want to try first? Each problem opens in the practice workspace, where your Python runs against the lesson's tests. To read the solution without trying first, open its Solution tab.

The lessons

Pairs worth reading together

  • Shortest subarray reaching a sum and Subarrays summing to k look almost the same. The first allows only positive numbers, so a sliding window works. The second allows negative numbers, which breaks the window; it needs prefix sums and a hash map.
  • Daily Temperatures and Sliding Window Maximum both throw away candidates that can never win. The second also lets candidates expire, which turns a stack into a deque.
  • Two Sum is a good first lesson. Its trick, rewriting a condition on a pair, comes back in the prefix-sum lesson.

How to study a lesson

  • Read the problem, then stop. Write the slow solution and say what makes it slow before you read step 2.
  • Finish it yourself. After the key observation, try to write the fast solution before reading it.
  • Come back in a few days. Rebuild the solution from a blank page. Recognizing an explanation is not the same as being able to produce it.

Every code block is plain Python 3. Our tests run each one and compare the fast solution with the slow one on thousands of random inputs. Passing tests make a bug unlikely, but they don't replace the argument in step 5.

The pattern chapters cover many more techniques in shorter form.