Simulate a Topic Message Broker with Subscription Tokens
Data Structure DesignAuto-graded · 15 test casesLast updated
Simulate a topic-based message broker from a command log, handling token issuance, ordered delivery records, and idempotent unsubscribes.
You are building a small in-memory message broker and must replay a log of commands against it. Each command either registers a listener on a named topic, broadcasts a message to a topic, or cancels an earlier registration.
You are given two lists of equal length:
operations: a list of command names.arguments: a list wherearguments[i]holds the arguments foroperations[i].
Process the commands in order, starting with an empty broker, and return one result per command.
Commands
"subscribe" with arguments [topic, listener_id]
- Register
listener_idontopic. - Every registration gets a new integer token. The first token issued is
1, and each latersubscribecommand gets the next integer (2,3, ...), whatever topic it targets. - The result is the issued token.
- Registering the same
listener_idon the same topic more than once is allowed. Each registration is independent, has its own token, and receives its own delivery.
"publish" with arguments [topic, payload]
- Look at all registrations currently active on
topic. - The result is a list with one entry
[listener_id, payload]per active registration, ordered by when the registrations were made (earliest first). - If the topic has no active registrations, or has never been used, the result is an empty list
[]. payloadcan be any JSON value (includingnull, numbers, strings, lists, or objects) and must be returned unchanged.
"unsubscribe" with arguments [token]
- If
tokenbelongs to a registration that is still active, remove it and returntrue. - Otherwise (the token was never issued, or was already cancelled) do nothing and return
false. - Removing a registration must not change the relative order of the remaining ones, and tokens are never reused.
Output
Return a list of results, one per command, in the same order as the input. Results are integers (tokens), lists of [listener_id, payload] pairs, or booleans, as described above.
Constraints
operationsandargumentshave the same length.- Every command name is one of
"subscribe","publish","unsubscribe". - Arguments always match the shape listed for their command.
- Tokens are integers starting at
1; onlysubscribecommands consume tokens. - Delivery is purely a returned record; no real callbacks are executed.
Examples
Example 1
Input: replay_broker_log(['subscribe', 'subscribe', 'publish', 'unsubscribe', 'publish'], [['news', 'alice'], ['news', 'bob'], ['news', {'headline': 'Update'}], [1], ['news', 'next']])
Output: [1, 2, [['alice', {'headline': 'Update'}], ['bob', {'headline': 'Update'}]], True, [['bob', 'next']]]
Example 2
Input: replay_broker_log(['publish', 'subscribe', 'subscribe', 'unsubscribe', 'unsubscribe', 'unsubscribe', 'publish'], [['empty', 7], ['x', 'same'], ['x', 'same'], [1], [1], [2], ['x', None]])
Output: [[], 1, 2, True, False, True, []]
Hints
Hint 1
Keep, per topic, an ordered collection of active registrations so a publish can list them in the order they were made.
Hint 2
To cancel by token alone you need a second lookup from token to topic; removing the entry from that lookup also tells you whether the token was still active.
Hint 3
A publish only reports registrations that exist at that moment, so build its result right then and copy the payload as-is; repeated listener ids are separate registrations.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep two structures while replaying the log:
topic_regs: maps each topic to a list of(token, listener_id)pairs in the order they were registered.token_topic: maps each active token to its topic.
A counter hands out tokens starting at 1.
- subscribe: take the next token, append
(token, listener_id)to the topic's list, record the token intoken_topic, and return the token. - publish: walk the topic's current list (or an empty one if the topic is unknown) and emit
[listener_id, payload]for each entry. The list is in registration order, so the output order is right, and duplicate listener ids naturally produce duplicate deliveries. - unsubscribe: pop the token from
token_topic. If it is missing, the token was never issued or was already cancelled, so returnFalse. Otherwise filter that entry out of the topic's list (keeping the order of the rest), delete the topic if it becomes empty, and returnTrue.
Why it is correct
The per-topic list only ever contains active registrations, since a registration is removed exactly when its token is popped from token_topic. Appending preserves registration order, and filtering preserves relative order. Tokens come from a monotonically increasing counter that only subscribe advances, so they are never reused, and a second unsubscribe of the same token finds nothing in token_topic and returns False.
Complexity
Let n be the number of commands. subscribe is O(1). publish is O(k) for k active registrations on the topic, which is the size of its output. unsubscribe is O(k) because of the list filter. Total time is O(n * k) in the worst case, and space is O(n) for the registrations plus the output. A per-topic ordered dictionary keyed by token would make unsubscribe O(1).
Reference solution
from typing import List
def replay_broker_log(operations: List[str], arguments: List[List]) -> List:
topic_regs = {} # topic -> list of (token, listener_id) in registration order
token_topic = {} # token -> topic for active registrations
next_token = 1
results = []
for op, args in zip(operations, arguments):
if op == "subscribe":
topic, listener_id = args
token = next_token
next_token += 1
topic_regs.setdefault(topic, []).append((token, listener_id))
token_topic[token] = topic
results.append(token)
elif op == "publish":
topic, payload = args
results.append(
[[listener_id, payload] for _, listener_id in topic_regs.get(topic, [])]
)
elif op == "unsubscribe":
(token,) = args
topic = token_topic.pop(token, None)
if topic is None:
results.append(False)
continue
topic_regs[topic] = [e for e in topic_regs[topic] if e[0] != token]
if not topic_regs[topic]:
del topic_regs[topic]
results.append(True)
else:
raise ValueError("unknown operation")
return results