A market order fills now at whatever prices exist. A market buy takes from resting sell orders, cheapest first, climbing to worse prices until it's filled or the sells run out; a market sell mirrors this against buy orders, highest first. Traders call it sweeping the book.
Implement sweep(resting, side, qty) -> tuple[int, int, int | None]. resting is a list of (side, price, qty) orders in no particular order; side and qty describe the market order. Return (filled, notional, worst_price): shares filled (less than qty if the book is thin), Σ price · shares, and the last (worst) price traded, or None if nothing filled. Don't modify resting.
book = [("sell", 102, 5), ("buy", 99, 4), ("sell", 101, 3), ("sell", 105, 10), ("buy", 100, 2)]
sweep(book, "buy", 6) # (6, 101*3 + 102*3, 102) = (6, 609, 102)
sweep(book, "sell", 5) # (5, 100*2 + 99*3, 99) = (5, 497, 99)
sweep(book, "sell", 50) # (6, 596, 99) only 6 shares were bid
sweep([("buy", 10, 1)], "buy", 3) # (0, 0, None) no sellers at all
Up to 10^5 orders; prices and quantities up to 10^9, qty up to 10^15. Integers only, no floats.
⭐ Bonus: a speed test with a 100,000-order book earns a star in O(n log n).
Show hint
keep the opposite side's orders, sort them best-first, and take min(remaining, order_qty) from each until remaining is 0.