LeetCode 2694: Event Emitter
Problem Description
Explanation
To implement the EventEmitter class, we can use a HashMap where the keys are event names and the values are lists of callback functions. When subscribing to an event, we add the callback function to the list of callbacks for that event. When emitting an event, we iterate through the list of callbacks for that event and call each callback with the provided arguments. Unsubscribing removes a specific callback function from the list of callbacks for the event.
Time Complexity
- Subscribing: O(1)
- Emitting: O(n) where n is the number of callbacks for the event
- Unsubscribing: O(n) where n is the number of callbacks for the event
Space Complexity
- O(m * n) where m is the number of events and n is the number of callbacks for each event
Solutions
import java.util.*;
class EventEmitter {
Map<String, List<Callback>> eventCallbacks;
public EventEmitter() {
eventCallbacks = new HashMap<>();
}
public void subscribe(String eventName, Callback callback) {
eventCallbacks.putIfAbsent(eventName, new ArrayList<>());
eventCallbacks.get(eventName).add(callback);
}
public void emit(String eventName, Object... args) {
List<Object> results = new ArrayList<>();
List<Callback> callbacks = eventCallbacks.getOrDefault(eventName, new ArrayList<>());
for (Callback cb : callbacks) {
results.add(cb.call(args));
}
System.out.println(results); // Returning results for demonstration
}
public void unsubscribe(String eventName, int index) {
if (eventCallbacks.containsKey(eventName)) {
List<Callback> callbacks = eventCallbacks.get(eventName);
if (index >= 0 && index < callbacks.size()) {
callbacks.remove(index);
}
}
}
private interface Callback {
Object call(Object... args);
}
}
Loading editor...