KatInterview

Two-Sided Order Book Matching with Unit Orders

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchheappriority-queuesimulation

Last updated

Simulate a simple exchange: buys and sells of size one arrive in sequence, cross against the best resting price, and you return the total value of all executed trades.

Order Book Simulator

You are building the core of a toy exchange. Every order is for exactly one unit and is described by a pair [side, price]:

  • side = 1 is a buy (bid).
  • side = -1 is a sell (ask).
  • price is a positive integer.

Orders arrive one at a time, in array order. Unfilled orders sit in an order book until a later order trades against them (these are called resting orders). Handle each arriving order as follows:

  1. Arriving buy at price p. While the book holds a resting sell priced <= p, trade against the resting sell with the lowest price. Both orders leave the book.
  2. Arriving sell at price p. While the book holds a resting buy priced >= p, trade against the resting buy with the highest price. Both orders leave the book.
  3. If the arriving order cannot trade (or has already traded), it is not added to the book. If it finds no counterparty, it is added to the book and rests there.

Assume each trade executes at the resting order's price, that is, the price of the order that was already in the book.

Return the sum of the prices of all trades after every order has been processed.

Example

orders = [[1,5], [1,7], [-1,6], [-1,4], [1,8], [-1,9]]

The sell at 6 trades with the resting buy at 7, and the sell at 4 trades with the resting buy at 5. The buy at 8 and the sell at 9 do not cross, so both rest. The answer is 7 + 5 = 12.

What to deliver

  • A function match_orders(orders) -> int.
  • The data structures you chose and why they support fast matching.
  • The time and space complexity.
  • How you resolve ties deterministically when several resting orders share the same best price.
  • Edge cases you would test.

Hints

Hint 1

Each side of the book only ever needs its best price: the lowest ask and the highest bid. Which structure gives you the minimum quickly, and how could you reuse it for a maximum?

Hint 2

If the best opposing price does not cross the arriving order, no other resting order on that side can cross it either. Think about why the book never contains a buy and sell that could trade with each other.

Hint 3

Store an arrival counter next to each price in the heap entries. Equal prices then fall back to earliest arrival first, which makes counterparty selection deterministic.