Lifespan Lookups for Orders and Order Groups in a Replay Log
Data Structure DesignAuto-graded · 15 test casesLast updated
Simulate a class through an operations list, tracking per-order and per-group start and end times so lookups run in constant time, with groups reporting 0 while any member is open.
Order and Group Lifespans
A trading system records the lifecycle of orders. Each order may belong to a named group (a "batch"), or may stand alone. You are given a replay of operations performed on a tracker object, and you must return what the tracker would output for each operation.
Operations
You receive two parallel lists, operations and arguments. The i-th operation is operations[i] and its argument list is arguments[i]. Operations are applied in order. Each operation is one of:
"process_event"with arguments[timestamp, action, order_id]or[timestamp, action, order_id, batch_id].actionis"CREATE": the orderorder_idopens attimestamp. If abatch_idis given (and is notnull), the order is a member of that batch. ACREATEmay omit the batch or passnullfor a standalone order.actionis"CLOSE": the orderorder_idfinishes attimestamp. No batch is supplied; the order's batch is the one it was created with.
"get_lifetime"with arguments[identifier]. The identifier may be an order ID or a batch ID.
Output for each operation
- For
process_event, the output isnull(None). - For
get_lifetime, the output isNoneif the identifier is not a known order or batch, otherwise a two-element list[start, end]:- Order ID:
startis the order's creation timestamp.endis its close timestamp, or0if it has not been closed yet. - Batch ID:
startis the smallest creation timestamp among all orders created so far in that batch.endis the largest close timestamp among the batch's orders, but it must be0if any order of the batch is still open at query time.
- Order ID:
Order IDs and batch IDs never collide: no string is used as both. A batch exists as soon as at least one order has been created with that batch ID. A query reflects only the events processed before it.
Return a list with exactly one entry per operation, in order.
Constraints
1 <= timestamp <= 10^9.- Each order is created at most once and closed at most once, and never closed before it is created.
- The total number of operations is at most
200,000. - Each
get_lifetimeshould be answerable inO(1)time; do not scan the members of a batch at query time. - Order and batch IDs are strings, and the two sets of IDs are disjoint.
Examples
Example 1
Input: replay_lifespans(['process_event', 'process_event', 'process_event', 'process_event', 'get_lifetime', 'get_lifetime', 'get_lifetime', 'get_lifetime', 'process_event', 'get_lifetime', 'get_lifetime'], [[100, 'CREATE', 'O1', 'B1'], [105, 'CREATE', 'O2', 'B1'], [110, 'CREATE', 'O3', None], [150, 'CLOSE', 'O1'], ['O1'], ['O2'], ['B1'], ['O3'], [180, 'CLOSE', 'O2'], ['B1'], ['UNKNOWN']])
Output: [None, None, None, None, [100, 150], [105, 0], [100, 0], [110, 0], None, [100, 180], None]
Hints
Hint 1
A query must not iterate over batch members, so each batch needs a summary that you keep up to date as events arrive.
Hint 2
For each batch, keep the earliest creation time, the latest close time seen so far, and a count of members that are still open.
Hint 3
A batch's end must be reported as 0 whenever its open count is above zero, even if some members have already closed and a latest close time exists. Do not use 'latest close is 0' as the open test.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because each lookup must be constant time, a batch cannot be scanned at query time. Instead, maintain two hash maps that are updated incrementally:
orders[order_id] = [start, end, batch_id], whereendis0while the order is open.batches[batch_id] = [min_start, max_end, open_count].
Processing the operations in order:
- CREATE: store the order with
end = 0. If it has a batch, either create the batch entry[timestamp, 0, 1]or lower itsmin_startand incrementopen_count. - CLOSE: set the order's
end. If the order has a batch, decrement that batch'sopen_countand raise itsmax_endto at least the close timestamp. - get_lifetime: if the identifier is an order, return
[start, end]. Otherwise, if it is a batch, return[min_start, 0 if open_count > 0 else max_end]. Otherwise returnNone.
Every process_event appends None to the results.
Why it is correct
- An order is created once and closed at most once, so its stored
endis0until its single close and the close timestamp afterward. min_startis the minimum over all creations in the batch, which is exactly the batch's start.open_countequals creations minus closes for the batch, so it is zero exactly when no member is open.max_endis the maximum close timestamp seen. It is only reported onceopen_countis zero, at which point every member has closed and it is the true latest close. While any member is open, the answer is forced to0, as required.- Since order and batch IDs are disjoint, checking orders first and then batches is unambiguous.
Complexity
- Time:
O(1)per operation on average, soO(N)overall. - Space:
O(O + B)for the number of distinct orders and batches; no member lists are stored.
Reference solution
from typing import List
def replay_lifespans(operations: List[str], arguments: List[List]) -> List[object]:
orders = {} # order_id -> [start, end (0 if open), batch_id]
batches = {} # batch_id -> [min_start, max_end, open_count]
results = []
for operation, args in zip(operations, arguments):
if operation == "process_event":
timestamp, action, order_id, *optional_batch = args
if action == "CREATE":
batch_id = optional_batch[0] if optional_batch else None
orders[order_id] = [timestamp, 0, batch_id]
if batch_id is not None:
if batch_id not in batches:
batches[batch_id] = [timestamp, 0, 1]
else:
batch = batches[batch_id]
batch[0] = min(batch[0], timestamp)
batch[2] += 1
else:
order = orders[order_id]
order[1] = timestamp
batch_id = order[2]
if batch_id is not None:
batch = batches[batch_id]
batch[2] -= 1
batch[1] = max(batch[1], timestamp)
results.append(None)
else:
(identifier,) = args
if identifier in orders:
start, end, _ = orders[identifier]
results.append([start, end])
elif identifier in batches:
start, end, open_orders = batches[identifier]
results.append([start, 0 if open_orders else end])
else:
results.append(None)
return results