NeetCode #970LC-2694MediumJavaScript
← Back to All Problems#970 · #2694 · Event Emitter(事件发射器)
📌 Problem Statement & Constraints
Implement an
EventEmitter class: subscribe(eventName, callback) registers a callback and returns an object with an unsubscribe() method; emit(eventName, args) synchronously invokes all callbacks for that event and returns an array of their results. Constraints: at most 10^4 calls.💡 Core Algorithmic Approaches
- Store listeners in a
Mapfrom event name to an array of callbacks. subscribecreates the array on demand, pushes the callback, and returns anunsubscribethat removes exactly that callback withindexOfplussplice.emitinvokes every callback in registration order, spreadsargs, and collects the results into an array.- When an event has no subscribers,
emitreturns an empty array.
💻 Benchmark Python3 Implementation
class EventEmitter {
constructor() {
this.events = new Map();
}
subscribe(event, cb) {
if (!this.events.has(event)) {
this.events.set(event, []);
}
const list = this.events.get(event);
list.push(cb);
return {
unsubscribe: () => {
const i = list.indexOf(cb);
if (i !== -1) list.splice(i, 1); // remove only this callback
}
};
}
emit(event, args = []) {
const list = this.events.get(event) || [];
return list.map(cb => cb(...args));
}
}⚡ Complexity Deep Dive
⏱️ Time Complexity
subscribe is O(1); emit and unsubscribe are O(k) over k listeners for the event.
💾 Space Complexity
O(m): m is the total number of callbacks.
⚠️ Interview Pitfalls & Follow-ups
- Rebuilding the array with
filterinunsubscribe: that removes every equal callback reference;spliceremoves only the intended one. - Using
forEachinemit: it returns nothing, but an array of results is required. - Passing
argswithout spreading: callbacks would receive a single array argument instead of separate parameters. - Throwing when the event has no subscribers:
emitshould return an empty array.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.