Trade Join With Expiring Partial Records
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a stream join that pairs order and price events by ID, using a min-heap with lazy deletion to expire unmatched partial records.
Joining Order and Price Events
A trading pipeline receives two kinds of events that refer to the same trade through a shared order_id:
- an order event carrying
symbolandquantity, - a price event carrying
price.
A trade is complete only when both halves have arrived, in either order. Until then, the half that has arrived is kept in a pending record. Pending records that wait too long are dropped.
You are given a list of commands and a parallel list of argument lists. Replay them in order and return one result per command.
Commands
| Command | Arguments | Meaning |
|---|---|---|
"init" | [timeout_ms] | Create a fresh engine with the given timeout. It is always the first command. |
"process_order" | [order_id, symbol, quantity, timestamp_ms] | Deliver an order event. |
"process_price" | [order_id, price, timestamp_ms] | Deliver a price event. |
Rules for handling an event with timestamp t
- Expire first. Before anything else, remove every pending record whose deadline is strictly less than
t. A record's deadline iscreation_timestamp + timeout_ms, wherecreation_timestampis the timestamp of the event that created the record. The only clock is thetof the event being handled. Do not keep a maximum of earlier timestamps, because timestamps may go backwards. - Store the part. If there is no pending record for
order_id, create one with deadlinet + timeout_ms. Then write the event's data into the record's order part or price part. If that part is already present, overwrite it. Overwriting never changes the record's deadline. - Complete the trade. If the record now has both parts, remove it and produce a completed trade. Otherwise the event produces no output.
An incoming event is never rejected for being late. It always goes through steps 2 and 3 after step 1.
Output
Return a list with one entry per command:
Nonefor"init".Nonefor an event that does not complete a trade.- For an event that completes a trade, a dictionary with the keys
"order_id","symbol","quantity","price". Values are exactly as supplied, with no type conversion.
Constraints
- The first command is always
"init", and it appears once. timeout_ms >= 0; timestamps are integers and may arrive out of order.order_idandsymbolare strings;quantityis an integer;priceis a number.- The number of commands is up to about 10^5, so the work per event should be roughly logarithmic, not proportional to the number of pending records.
- Commands other than the three above do not occur.
Examples
Example 1
Input: run_trade_join(['init', 'process_order', 'process_price'], [[20], ['101', 'AAPL', 10, 1000], ['101', 150, 1050]])
Output: [None, None, None]
Example 2
Input: run_trade_join(['init', 'process_order', 'process_order', 'process_price'], [[20], ['101', 'AAPL', 10, 1000], ['101', 'AAPL', 10, 1040], ['101', 150, 1041]])
Output: [None, None, None, {'order_id': '101', 'symbol': 'AAPL', 'quantity': 10, 'price': 150}]
Hints
Hint 1
Keep a dictionary from order_id to a pending record holding the order part, the price part, and the record's deadline. A record completes as soon as both parts are present.
Hint 2
Expiry is based on the creation timestamp of the record, not on the latest overwrite. Push (deadline, token, order_id) into a min-heap when a record is created, and pop while the top deadline is strictly less than the current event's timestamp.
Hint 3
A record can be completed and removed, and the same order_id can later start a new record, so heap entries can go stale. Give each record a unique token and delete from the dictionary only if the stored token matches the popped one.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat this as a small simulation with three pieces of state:
- A dictionary of pending records, keyed by
order_id. Each record holds the order part and/or the price part, plus a unique token. When an event arrives, the code finds or creates the record, writes its part, and checks whether both parts are now present. If they are, it removes the record and returns the completed trade. Because both event types write into the same record, the arrival order does not matter. - A min-heap of
(deadline, token, order_id), pushed once when a record is created, withdeadline = creation_timestamp + timeout_ms. Before each event, the code pops entries while the top deadline is strictly less than the event's timestamp. This avoids scanning every pending record. - Lazy deletion with tokens. Completed records are not removed from the heap. A popped heap entry deletes a dictionary record only if the record still exists and carries the same token. If the record was completed, or replaced by a newer record for the same
order_id, the token differs and the entry is ignored.
Why it is correct
- Every live record has exactly one heap entry with its true deadline. Overwriting a part never creates a new heap entry, so the deadline stays tied to the record's creation, as the rules require.
- The heap yields deadlines in increasing order, so popping while
deadline < tremoves exactly the live records that satisfy the expiry rule, and nothing else. Stale entries are harmless because of the token check. - Purging uses the current event's timestamp only, with no running maximum, which matches the rule for out-of-order timestamps.
- Purging happens before the event is stored, so a record that has just expired cannot be matched by the event that revealed its expiry. The event instead starts a fresh record.
- The deadline comparison is strict, so a record whose deadline equals
tis still alive.
Complexity
Each event does one dictionary lookup and at most one heap push. Each heap entry is pushed once and popped at most once, so the total time is O(n log n) for n commands, or O(log n) amortized per event. Space is O(n) for the pending records plus stale heap entries.
Reference solution
import heapq
from typing import Dict, List, Optional
def run_trade_join(commands: List[str], params: List[List]) -> List[Optional[Dict]]:
timeout = 0
pending = {} # order_id -> record
heap = [] # (deadline, token, order_id)
next_token = 0
results = []
def purge(now):
while heap and heap[0][0] < now:
_, token, oid = heapq.heappop(heap)
rec = pending.get(oid)
if rec is not None and rec["token"] == token:
del pending[oid]
def add(order_id, kind, value, ts):
nonlocal next_token
purge(ts)
rec = pending.get(order_id)
if rec is None:
token = next_token
next_token += 1
rec = {"token": token}
pending[order_id] = rec
heapq.heappush(heap, (ts + timeout, token, order_id))
rec[kind] = value
if "order" in rec and "price" in rec:
del pending[order_id]
return {
"order_id": order_id,
"symbol": rec["order"]["symbol"],
"quantity": rec["order"]["quantity"],
"price": rec["price"],
}
return None
for cmd, args in zip(commands, params):
if cmd == "init":
timeout = args[0]
pending = {}
heap = []
next_token = 0
results.append(None)
elif cmd == "process_order":
order_id, symbol, quantity, ts = args
results.append(add(order_id, "order",
{"symbol": symbol, "quantity": quantity}, ts))
elif cmd == "process_price":
order_id, price, ts = args
results.append(add(order_id, "price", price, ts))
else:
raise ValueError("Unknown operation: " + cmd)
return results