1747. Order Book Matcher

Medium3.5 points estimatedHeapSimulationGreedy

A small exchange matches orders as they arrive in sequence. Order i is for amounts[i] units at limit price prices[i]; sides[i] = 0 is a buy and 1 is a sell. An arriving buy trades against resting sells priced at or below its price, cheapest first, and an arriving sell trades against resting buys priced at or above its price, highest first. Orders at the same price are served in arrival order, each trade uses as many units as both orders allow, and whatever quantity of the arriving order is left over rests in the book for later orders.

Return the total number of units traded over all orders, as a long. Keep a min-heap of resting sells and a max-heap of resting buys for O(n log n) time and O(n) space.

Example 1

Input:
prices = [10,12,9,11]amounts = [5,4,3,6]sides = [1,1,0,0]
Output:
5
Explanation:

The buy of 6 at price 11 meets only the resting sell of 5 at price 10 (the sell at 12 is too expensive), so 5 units trade and 1 unit rests.

Example 2

Input:
prices = [8,7,7], amounts = [10,4,8], sides = [0,1,1]
Output:
10
Explanation:

The sell of 4 takes 4 units from the resting buy of 10, then the sell of 8 takes the remaining 6, so 10 units trade in total.

Example 3

Input:
prices = [5,6], amounts = [1,1], sides = [0,1]
Output:
0
Explanation:

The buy at 5 and the sell at 6 never cross, so nothing trades.

Constraints

1 ≤ n ≤ 105 (n = prices.length = amounts.length = sides.length)
1 ≤ prices[i] ≤ 109
1 ≤ amounts[i] ≤ 109
sides[i] is 0 or 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…