Sharded Order Book Simulator with Cancel and Open Lookup
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a sharded order book that routes users with FNV-1a, enforces a one-way status lifecycle, and answers per-user open-order queries in placement order.
Sharded Order Book Simulator
You are given a batch of requests for a small order book. Process them in order and return one result per request.
Users are spread over shard_count shards. A user's shard is fnv1a_32(user_id) % shard_count, where fnv1a_32 is the 32-bit FNV-1a hash of the UTF-8 bytes of user_id:
- Start with
h = 2166136261. - For each byte
bof the UTF-8 encoding, doh = h XOR b, thenh = (h * 16777619) mod 2^32.
Every order has one of three statuses: OPEN, FILLED, or CANCELLED. A new order starts as OPEN. An OPEN order may later become CANCELLED. Once an order leaves OPEN, its status never changes again.
Requests
Request i has the name commands[i] and the argument list params[i].
"place_order"with[user_id, order_id, symbol, amount]: create a newOPENorder owned byuser_id, stored in that user's shard.- Order IDs are unique across the whole system and forever. If
order_idwas ever used before (including by an order that is now cancelled, and regardless of owner), do nothing and returnFalse. - Otherwise, store the order and return
True.
- Order IDs are unique across the whole system and forever. If
"cancel_order"with[user_id, order_id]: look the order up in the shard ofuser_id.- If the order does not exist there, belongs to a different user, or is not
OPEN, change nothing and returnFalse. - Otherwise, set its status to
CANCELLEDand returnTrue.
- If the order does not exist there, belongs to a different user, or is not
"get_user_orders"with[user_id]: return a list of all orders of that user that are currentlyOPEN, in the order they were placed (oldest first). Each order is a dictionary with exactly these keys:"order_id","user_id","symbol","amount","status". Theamountis returned exactly as it was supplied. Thestatusof every returned order is"OPEN". If the user has no open orders, return[]. The returned dictionaries must be copies, so later requests never alter results already produced.- Any other command name is invalid and must raise
ValueError.
Task
Implement process_order_requests(shard_count, commands, params) so that it returns the list of results, one per request, in input order.
A good solution answers place_order and cancel_order in O(1) average time. get_user_orders should take time proportional to the number of that user's open orders, not to the total number of orders.
Constraints
1 <= shard_count <= 1024len(commands) == len(params), and the total number of requests is up to about 10^6.user_id,order_id, andsymbolare strings.user_idmay contain non-ASCII characters.amountis a number (int or float).- The result list contains booleans for
place_orderandcancel_order, and lists of dictionaries forget_user_orders.
Examples
Example 1
Input: process_order_requests(4, ['place_order', 'place_order', 'cancel_order', 'get_user_orders'], [['user1', 'ordA', 'BTC', 1], ['user1', 'ordB', 'ETH', 2], ['user1', 'ordA'], ['user1']])
Output: [True, True, True, [{'order_id': 'ordB', 'user_id': 'user1', 'symbol': 'ETH', 'amount': 2, 'status': 'OPEN'}]]
Example 2
Input: process_order_requests(1, ['place_order', 'get_user_orders'], [['alice', 'o1', 'AAPL', 3.5], ['alice']])
Output: [True, [{'order_id': 'o1', 'user_id': 'alice', 'symbol': 'AAPL', 'amount': 3.5, 'status': 'OPEN'}]]
Example 3
Input: process_order_requests(2, ['place_order', 'place_order', 'cancel_order', 'get_user_orders'], [['u1', 'x', 'BTC', 1], ['u2', 'y', 'ETH', 4], ['wrong-user', 'x'], ['u1']])
Output: [True, True, False, [{'order_id': 'x', 'user_id': 'u1', 'symbol': 'BTC', 'amount': 1, 'status': 'OPEN'}]]
Hints
Hint 1
Cancelled orders must still remember their IDs, otherwise an old order_id could be placed again. Keep a record of every ID ever used.
Hint 2
Keep a second index per user that holds only the OPEN orders, using a dictionary so insertion order (placement order) is preserved and deletion is O(1).
Hint 3
For FNV-1a, XOR the byte in first, then multiply by the prime and mask with 0xFFFFFFFF. Remove a user's entry from the open index when their last open order is cancelled, and return copies of the order dictionaries.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Simulate the order book directly, with the right indexes so each request is cheap.
- Routing. Compute the 32-bit FNV-1a hash of the user ID (XOR the byte, then multiply by
16777619and mask to 32 bits) and take it moduloshard_count. Each shard holds two maps:orders:order_id -> order dict, used for O(1) cancel lookups.open:user_id -> {order_id -> order dict}, containing onlyOPENorders. Python dicts keep insertion order, so iterating one user's inner dict yields orders oldest first.
- Global ID set. A set
used_idsrecords every order ID ever placed. It is never shrunk, so a cancelled order's ID cannot be reused, and duplicates are rejected regardless of owner. - place_order. If the ID is already used, return
False. Otherwise create the order with statusOPEN, add it to the shard'sordersand to the owner's open map, and returnTrue. - cancel_order. Look the order up in the shard of the given user. If it is missing, owned by someone else, or not
OPEN, returnFalse. Otherwise mark itCANCELLED, delete it from the user's open map (removing the user's entry if it becomes empty), and returnTrue. - get_user_orders. Iterate only that user's open map and return copies of the dictionaries.
- An unknown command raises
ValueError.
Why it is correct
The invariant is that an order appears in open[user] exactly when its status is OPEN. place_order establishes it by adding to both maps. Cancel is the only status change, and it flips the status and removes the order from the open map in the same step. Because cancel requires OPEN first, a terminal order can never change again. IDs are never removed from used_ids, so uniqueness holds forever. The owner check in cancel rejects requests from the wrong user whether they land in the same shard or a different one. Dict insertion order gives the required oldest-first output, and returning copies prevents later mutations from altering earlier results.
Complexity
place_orderandcancel_order: O(L) to hash a user ID of length L, plus O(1) average for the dictionary work.get_user_orders: O(L + K), where K is the number of that user's open orders.- Space: O(M) for M orders ever placed, since cancelled orders are retained for ID uniqueness.
Reference solution
from typing import List
def process_order_requests(shard_count: int, commands: List[str], params: List[List]) -> List:
def fnv1a_32(text: str) -> int:
h = 2166136261
for byte in text.encode("utf-8"):
h ^= byte
h = (h * 16777619) & 0xFFFFFFFF
return h
# Each shard: all orders by id, and open orders grouped by user (insertion ordered).
shards = [{"orders": {}, "open": {}} for _ in range(shard_count)]
used_ids = set()
results = []
for command, args in zip(commands, params):
if command == "place_order":
user_id, order_id, symbol, amount = args
if order_id in used_ids:
results.append(False)
continue
shard = shards[fnv1a_32(user_id) % shard_count]
order = {
"order_id": order_id,
"user_id": user_id,
"symbol": symbol,
"amount": amount,
"status": "OPEN",
}
shard["orders"][order_id] = order
shard["open"].setdefault(user_id, {})[order_id] = order
used_ids.add(order_id)
results.append(True)
elif command == "cancel_order":
user_id, order_id = args
shard = shards[fnv1a_32(user_id) % shard_count]
order = shard["orders"].get(order_id)
if order is None or order["user_id"] != user_id or order["status"] != "OPEN":
results.append(False)
continue
order["status"] = "CANCELLED"
open_orders = shard["open"][user_id]
del open_orders[order_id]
if not open_orders:
del shard["open"][user_id]
results.append(True)
elif command == "get_user_orders":
user_id = args[0]
shard = shards[fnv1a_32(user_id) % shard_count]
open_orders = shard["open"].get(user_id, {})
results.append([dict(o) for o in open_orders.values()])
else:
raise ValueError(f"unknown command: {command}")
return results