KatInterview

Tackling Long-Winded Data Structure Design Problems Step by Step

Data Structure DesignModel answer
MediumModel answerData Structure Designdata-structure-designorder-bookinvariants

Last updated

Describe a repeatable process for data-structure designs that are simple to state but long to code, then apply it to a price-time-priority limit order book.

Some design questions have behavior you can explain in a minute, but the implementation runs to a hundred lines or more with many interacting cases. Think of an in-memory cache with several eviction rules, a rate limiter with multiple windows, or a matching engine.

Explain the process you would follow in a live coding session for a problem like this. Cover:

  1. How you clarify the operations and constraints before writing code.
  2. How you model states and transitions.
  3. How you choose the core data structures.
  4. How you reason about per-operation time and space complexity.
  5. Which boundary cases you enumerate.
  6. How you organize the code and tests to keep bugs down.

Make the answer concrete with a worked example: an order book for one instrument with these operations.

  • add(id, side, price, qty) adds a buy ("B") or sell ("S") limit order. It first matches against the opposite side, then rests any remainder. It returns the list of fills.
  • cancel(id) removes a resting order and returns whether it existed.
  • best_bid() and best_ask() return the best price on each side, or None if the side is empty.

Assume integer prices, price-then-time priority, and trades executing at the resting order's price.

Hints

Hint 1

Before choosing structures, write down the facts that must always hold between calls (for example, 'an order is indexed if and only if it sits in a price level'). Most bugs in long designs are two structures disagreeing.

Hint 2

Ask what each operation needs: best price, FIFO within a price, and removal of an arbitrary order by id. Pick one structure per need, and consider deleting lazily instead of keeping a heap perfectly in sync.

Hint 3

Put 'remove a resting order' in a single helper, and write an invariant-checking function you can call after every operation in your tests.