Top-of-Book Quotes per Venue and Across All Venues
Data Structure DesignAuto-graded · 13 test casesLast updated
Aggregate order records by price level to answer per-venue and market-wide best bid and ask queries, summing the size at the best price.
You are given a fixed collection of resting orders from several trading venues, followed by a batch of queries. Your job is to answer each query with the best buy price and best sell price, along with the total size available at each of those prices.
Input
orders: a list of order records. Each record is a list[venue_id, price, quantity, side]:venue_id: a string or an integer naming the venue.price: a positive number.quantity: a positive integer.side:"B"for a buy order (bid) or"A"for a sell order (ask).
queries: a list of query names, each either"get_exchange_bbo"or"get_nbbo".query_args: a list with the same length asqueries. Entryiholds the arguments forqueries[i]:- for
"get_exchange_bbo", a one-element list[venue_id]; - for
"get_nbbo", an empty list[].
- for
The orders never change between queries.
Definitions
- The best bid in a scope is the highest price among bid orders in that scope.
- The best ask in a scope is the lowest price among ask orders in that scope.
- The size of a best quote is the sum of the quantities of all orders on that side that sit exactly at that best price within the scope.
- For
"get_exchange_bbo", the scope is only the orders of the given venue. - For
"get_nbbo", the scope is the orders of all venues combined. If several venues quote the same best price, their quantities are added together.
Output
Return a list with one result per query, in the same order as queries. Each result is a two-element list [best_bid, best_ask], where each side is either:
[price, total_quantity](a list, not a tuple), orNoneif that side has no orders in the scope.
Further rules:
- A venue that does not appear in
ordersyields[None, None](no error). - If a query name is not one of the two supported names, raise
ValueError. - Do not adjust or "uncross" the data: if a best bid is at or above a best ask, report both as they are.
- Prices are compared by value as dictionary keys would be, so
100and100.0count as the same price level. Venue ids"1"and1are different venues.
Constraints
- The number of orders can be large (on the order of 10^5 or more), so the batch of queries should be answered efficiently rather than by rescanning all orders each time.
price > 0,quantity > 0.sideis always"B"or"A".len(queries) == len(query_args).ordersmay be empty.
Examples
Example 1
Input: top_of_book_queries([[1, 100, 10, 'B'], [1, 101, 5, 'A'], [2, 100, 7, 'B'], [2, 99, 4, 'A']], ['get_exchange_bbo', 'get_exchange_bbo', 'get_nbbo'], [[1], [2], []])
Output: [[[100, 10], [101, 5]], [[100, 7], [99, 4]], [[100, 17], [99, 4]]]
Hints
Hint 1
Because the orders never change, you can group them once up front instead of rescanning for every query.
Hint 2
For each scope (every venue, plus one combined scope) and each side, keep a map from price to total quantity at that price.
Hint 3
The best bid is the maximum key of the bid map and the best ask is the minimum key of the ask map; the value stored under that key is already the summed size. Build the combined scope in the same pass so ties across venues are summed correctly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The orders are static, so we process them once and answer every query from the aggregated data.
For each scope (each venue, plus one combined scope covering all venues) and each side, we keep a dictionary mapping price -> total quantity at that price. Every order is added to its venue's dictionary and to the combined dictionary in the same pass.
To answer a query:
- The best bid is the entry with the largest key in the bid dictionary.
- The best ask is the entry with the smallest key in the ask dictionary.
- The value stored under that key is already the summed size, so we return
[price, size]. - An empty dictionary means that side does not exist, so we return
None. - An unknown venue is treated as having empty dictionaries, giving
[None, None]. - An unrecognised query name raises
ValueError.
Why it is correct
- After ingestion,
levels[p]equals the sum of quantities of all orders in that scope and side with pricep, since each order contributes exactly once to its venue map and once to the combined map. - The best bid and best ask are by definition the max and min price keys, and the stored value is exactly the required summed size.
- The combined map sums over all venues per price, so ties for the market-wide best price across venues are added together correctly.
- Nothing is adjusted when bid and ask cross, matching the requirement to report both sides as they are.
Complexity
Let N be the number of orders, L the number of distinct price levels in a scope, and Q the number of queries.
- Building the maps takes O(N) time and O(N) space.
- Each query as written costs O(L) because it takes a max or min over the keys. Since the data is static, the best quotes of each scope can be cached after building, which makes every query O(1) with O(N) total preprocessing. Outputs are identical.
If orders could be added or cancelled, a heap per side with lazy deletion, or a sorted container, would keep updates at O(log L).
Reference solution
from typing import List
def top_of_book_queries(orders: List[List], queries: List[str], query_args: List[List]) -> List[List]:
venues = {}
combined = {"B": {}, "A": {}}
for venue_id, price, quantity, side in orders:
book = venues.setdefault(venue_id, {"B": {}, "A": {}})
book[side][price] = book[side].get(price, 0) + quantity
combined[side][price] = combined[side].get(price, 0) + quantity
def best(levels, side):
if not levels:
return None
price = max(levels) if side == "B" else min(levels)
return [price, levels[price]]
results = []
for name, args in zip(queries, query_args):
if name == "get_exchange_bbo":
book = venues.get(args[0], {"B": {}, "A": {}})
results.append([best(book["B"], "B"), best(book["A"], "A")])
elif name == "get_nbbo":
results.append([best(combined["B"], "B"), best(combined["A"], "A")])
else:
raise ValueError("Unknown operation")
return results