Pattern

State machine

Name the small set of situations something can be in, then define exactly which transitions between them are legal — as a DP recurrence or as real code.

What it is

A state machine problem asks you to model something that moves between a small, fixed set of situations over time, where what happens next depends only on which situation you're currently in — never on the full history that got you there. In a coding/DP context, this means defining a handful of named states per step (holding a share versus not, which color the previous item used) and a recurrence for how each state's best value updates from the states it can legally follow. In a system-design/LLD context, it means the same idea made literal: named state classes, each exposing only the operations legal in that state, with everything else rejected by default. Both are the same discipline — enumerate the states, then enumerate exactly which transitions between them are allowed.

When it applies

Tells in the problem

The classic mistake

The recurring DP-side mistake is collapsing two states that look similar into one and missing the specific transition that distinguishes them — for example, treating "sold today" and "free to buy" as the same "not holding a share" situation, when the entire cooldown rule lives in the one-day delay between them. The fix is to ask, for every pair of states that seem mergeable, whether there's an edge allowed from one but not the other; if such an edge exists, they must stay separate. The recurring LLD-side mistake is the opposite failure mode: building one state class or enum branch per possible input rather than per situation, so the code ends up with the same if chain repeated in every method instead of each state class simply omitting (or rejecting by default) the operations that don't apply to it.

Questions to start with

All 3 state machine questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.