Ctrl K

Unfilled Exchange Orders

Medium
An exchange keeps an order book that starts empty. Batches of orders arrive from the list orders one after another: a triple [price, amount, side] stands for amount identical orders at price price, where side = 0 is a buy and side = 1 is a sell. Batches, and the orders inside each batch, are processed strictly in order, one at a time. When a buy order arrives, the exchange looks at the cheapest sell order in the book. If its price is no higher than the buy price, both orders are filled and the sell order leaves the book. Otherwise the buy order joins the book. A sell order works the other way round: the exchange takes the highest buy order in the book; if its price is no lower than the sell price, both are filled, otherwise the sell order joins the book. Return how many orders are left in the book once every batch has been processed. The number can be large, so return it modulo 10⁹ + 7.
Example 1
orders=[[20, 3, 1], [18, 2, 0], [25, 4, 0]] → 3

3 sell orders at 20 wait in the book. 2 buy orders at 18 fall short of 20 and wait too. Of the 4 buy orders at 25, three take the sells at 20 and one stays. The book holds 2 buys at 18 and 1 buy at 25, so 3 in total.

Example 2
orders=[[10, 5, 0], [8, 5, 1]] → 0

A sell at 8 is no higher than a buy at 10, so all 5 sells match the 5 buys and the book ends up empty.

Example 3
orders=[[5, 1000000000, 1], [5, 1000000000, 1]] → 999999993

There are no buys, so all 2·10⁹ sells remain; the answer is 2·10⁹ modulo 10⁹ + 7.

Constraints
  • 1 ≤ len(orders) ≤ 10⁵
  • 1 ≤ price, amount ≤ 10⁹
  • side is 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShuttle Seat Plan MediumHiring From Both Ends of the Line MediumCross Out the Smallest First MediumRounds of Row Maximums MediumFuse the Two Lightest Medium
loading Python…
Input
orders=[[20, 3, 1], [18, 2, 0], [25, 4, 0]]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 116 tests on the server, hidden ones included.