Match Buy and Sell Orders in a Price-Time Priority Order Book

Last updated: November 29, 2026

Quick Overview

Build the core of a marketplace order book: orders arrive one at a time as (side, price, quantity). A buy executes against the cheapest resting sells priced at or below it, a sell against the highest resting buys at or above it, oldest first at equal prices, at the resting order's price. Return the list of trades and the total resting quantity left.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Build the core of a marketplace order book: orders arrive one at a time as (side, price, quantity). A buy executes against the cheapest resting sells priced at or below it, a sell against the highest resting buys at or above it, oldest first at equal prices, at the resting order's price. Return the list of trades and the total resting quantity left.

Asked in Amazon onsites for teams that run pricing and auction-style systems. The interviewer checks the two-heap design, partial fills, time priority via sequence numbers, and whether you can talk about what changes at exchange scale.

What the Interviewer Expects
  • Uses a min-heap for asks and a max-heap for bids
  • Breaks price ties by arrival sequence
  • Handles partial fills on both sides
  • Executes at the resting order's price
  • Analyzes O(log n) per fill
Key Topics to Cover
heap
simulation
order book
priority queue
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Add order cancellation by ID in O(log n).
  • How would you support market orders?
  • How would you shard or replicate this for high availability?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: list of (side, price, qty) with side in {'buy', 'sell'}, positive integers. Output: (trades, resting) where trades is a list of (price, qty) in execution order and resting is the sum of quantit...

High-Level Design

Keep asks in a min-heap keyed by (price, seq) and bids in a max-heap keyed by (-price, seq), where seq is the arrival index so older orders win ties. For an incoming buy, while it has quantity and the...


Submit Your Answer
Markdown supported