Match Buy and Sell Orders in an Ad Inventory Exchange Backlog
Last updated: November 29, 2026
Quick Overview
Orders arrive as (price, amount, type). A buy matches the cheapest resting sell with price <= its price; a sell matches the highest resting buy with price >= its price. Unmatched quantity rests in the backlog. Return the total resting amount at the end.
0
0
0 solved
Orders arrive as (price, amount, type). A buy matches the cheapest resting sell with price <= its price; a sell matches the highest resting buy with price >= its price. Unmatched quantity rests in the backlog. Return the total resting amount at the end.
A Google onsite simulation styled after an ad exchange order book in the display ads stack. The interviewer checks two heaps (max for buys, min for sells), partial fills and the loop that drains multiple levels.
What the Interviewer Expects
- Keeps a max-heap of buys and a min-heap of sells
- Handles partial fills across several resting orders
- Rests the remainder in the correct heap
- Uses modular arithmetic if asked
- States O(n log n)
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Support order cancellation
- Return the trade log with prices
- How would you make this fault tolerant across replicas?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: list of
(price, amount, side)with side 0 = buy and 1 = sell, in arrival order. - Matching follows best price first. A trade reduces both orders by the matched amount.
- Output: total amoun...
High-Level Design
An order book is two priority queues. Buys are a max-heap by price (store negated), sells a min-heap. When a buy arrives, while it still has amount and the best sell has price <= its price, trade `min...