Process Event Listener Operations
Data Structure DesignAuto-graded · 15 test casesLast updated
Tests understanding of the observer pattern through ordered listener management, callback registration/removal, and event dispatch simulation.
You are building a system that tracks event listener registrations and dispatches. Given a sequence of operations on an event system, simulate the behavior and return the results.
Your function receives two parallel lists:
operations: a list of operation names ("on","off", or"emit")arguments: corresponding arguments for each operation
Operations:
-
on(event_name, listener_id): Register a listener (identified by a string or number) for the given event name. If the same listener is registered multiple times, it should trigger multiple times when the event fires. Listeners fire in the order they were registered. -
off(event_name, listener_id): Unregister one instance of the specified listener for the given event. If the listener was registered multiple times, only the first registration is removed. If the listener was never registered or the event doesn't exist, this is a no-op. -
emit(event_name, *args): Trigger all listeners registered for the event, passing any additional arguments. Return a list of invocations in registration order, where each invocation is[listener_id, args_list]. If no listeners are registered for the event, return an empty list.
Return Value:
A list with one entry per operation:
onandoffoperations returnNoneemitoperations return a list of[listener_id, arguments]pairs representing each listener invocation in order
Constraints:
- 1 ≤ len(operations) ≤ 1000
- Event names are always strings
- Listener identifiers can be strings or integers
emitcan have 0 or more additional arguments beyond the event name- Operations on different event names are independent
Examples
Example 1
Input: process_event_operations(['on', 'emit', 'off', 'emit'], [['greet', 'greet'], ['greet', 'Alice'], ['greet', 'greet'], ['greet', 'Bob']])
Output: [None, [['greet', ['Alice']]], None, []]
Example 2
Input: process_event_operations(['on', 'on', 'emit', 'off', 'emit'], [['update', 'a'], ['update', 'b'], ['update', 1, 2], ['update', 'a'], ['update', 3]])
Output: [None, None, [['a', [1, 2]], ['b', [1, 2]]], None, [['b', [3]]]]
Example 3
Input: process_event_operations(['emit', 'off', 'on', 'emit'], [['missing', 1], ['x', 'f'], ['x', 'f'], ['x']])
Output: [[], None, None, [['f', []]]]
Hints
Hint 1
Store listeners for each event in a list to preserve registration order
Hint 2
Use dictionary.get() with a default empty list to handle events that don't exist yet
Hint 3
The remove() method on a list only removes the first matching element, which gives you the correct behavior for off
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is maintaining an ordered collection of listeners for each event and processing operations that modify or query this state.
Data Structure Choice:
Use a dictionary mapping event names to lists of listener identifiers. Lists preserve insertion order, which ensures listeners fire in registration order during emission.
Operation Implementation:
-
Registration (
on): Append the listener to the event's list. Usesetdefaultto create an empty list if this is the first listener for that event. Duplicate registrations are allowed—the same listener can appear multiple times and will fire multiple times. -
Unregistration (
off): Use list'sremove()method, which removes only the first occurrence. If the listener isn't present,remove()raisesValueError, which we catch and ignore. This makes the operation safe even for non-existent events or listeners. -
Emission (
emit): Unpack the arguments to separate the event name from any additional parameters. Build a list of invocation records by iterating through the registered listeners. If the event has no listeners (or doesn't exist),get()returns an empty list, producing an empty result.
Why This Works:
- Ordering guarantee: Lists maintain insertion order. We only append (never prepend or insert), and
remove()doesn't reorder remaining elements. - Duplicate handling: Lists naturally allow duplicates. A listener registered twice appears twice in the list and fires twice.
- Symmetry: n
onoperations require noffoperations to fully remove a listener, matching standard event emitter semantics. - Isolation: Each event has its own list, so operations on different events never interfere.
- Safe non-existence: Using
get()with defaults and catchingValueErrormeans operations on unknown events or listeners are harmless no-ops.
Complexity:
Let k = number of listeners for a specific event, n = total operations.
- Time: O(n·k) worst case. Each
onis O(1) amortized. Eachoffis O(k) for the linear scan inremove(). Eachemitis O(k) to build the result. - Space: O(total registrations) for the dictionary, plus O(n·k·a) for the output, where a is the average argument count per emit.
The off operation is O(k) only for that event's listener list, not across all events. In practice, k is usually small (< 10 listeners per event), making this efficient.
Edge Cases Handled:
- Emitting an event with no listeners returns
[] - Removing a never-registered listener is a no-op
- The same listener registered multiple times fires multiple times; a single
offremoves only one instance - Emitting with zero additional arguments produces
[listener_id, []]for each listener
from typing import List
def process_event_operations(operations: List[str], arguments: List[List]) -> List:
event_listeners = {}
output = []
for op, args in zip(operations, arguments):
if op == "on":
event_name, listener_id = args
event_listeners.setdefault(event_name, []).append(listener_id)
output.append(None)
elif op == "off":
event_name, listener_id = args
listener_list = event_listeners.get(event_name, [])
try:
listener_list.remove(listener_id)
except ValueError:
pass
output.append(None)
elif op == "emit":
event_name, *extra_args = args
invocations = [
[listener_id, extra_args]
for listener_id in event_listeners.get(event_name, [])
]
output.append(invocations)
else:
raise ValueError(f"Unknown operation: {op}")
return output