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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

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
Heap
Order Book
Simulation
Two Heaps
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
  • 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 Problems
Sample 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...


Submit Your Answer
Markdown supported