Limit Order Book Matching Engine
Build the core of an exchange matching engine. orders arrive in sequence; each is a limit order { id, side, price, qty } with side either "buy" or "sell".
An incoming buy matches resting sells whose price is <= its price; an incoming sell matches resting buys whose price is >= its price. Among eligible resting orders, the best price goes first (lowest ask for a buy, highest bid for a sell), and on equal prices the order that arrived earlier goes first. Each match trades min(remaining incoming qty, resting qty) at the resting order's price. Matching continues until the incoming order is filled or nothing eligible is left; any remainder then rests in the book.
Return { trades, bids, asks }. trades lists { buyId, sellId, price, qty } in execution order. bids lists the resting buys { id, price, qty } sorted by price descending then arrival; asks lists resting sells sorted by price ascending then arrival. Fully filled orders are removed.
Example 1
Input: orders = [{"id":"s1","side":"sell","price":101,"qty":5},{"id":"s2","side":"sell","price":100,"qty":3},{"id":"b1","side":"buy","price":101,"qty":6},{"id":"b2","side":"buy","price":99,"qty":4}] Output: {"trades":[{"buyId":"b1","sellId":"s2","price":100,"qty":3},{"buyId":"b1","sellId":"s1","price":101,"qty":3}],"bids":[{"id":"b2","price":99,"qty":4}],"asks":[{"id":"s1","price":101,"qty":2}]} Explanation: b1 first takes the cheaper s2, then 3 of s1; b2 is too low to trade and rests.
Example 2
Input: orders = [{"id":"a","side":"sell","price":100,"qty":2},{"id":"b","side":"sell","price":100,"qty":2},{"id":"c","side":"buy","price":100,"qty":3}] Output: {"trades":[{"buyId":"c","sellId":"a","price":100,"qty":2},{"buyId":"c","sellId":"b","price":100,"qty":1}],"bids":[],"asks":[{"id":"b","price":100,"qty":1}]}
Constraints
- 0 <= orders.length <= 2000
- 1 <= price <= 10^6
- 1 <= qty <= 10^6
- ids are unique
Hint 1
Keep each side sorted by (price priority, arrival) so the best resting order is always at the front.
Hint 2
An order that partly rests keeps its original arrival time.
Discussion 0
Join free to post in the discussion.
Good practice for: Backend Developer, Full Stack Developer, Blockchain Developer, Data Engineer, Automation Test Engineer, Cloud Engineer
Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.