LeetCode 2694: Event Emitter Solution
Master LeetCode problem 2694 (Event Emitter), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2694. Event Emitter
Problem Explanation
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
Solution Code
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);
}
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2694 (Event Emitter)?
This page provides optimized solutions for LeetCode problem 2694 (Event Emitter) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2694 (Event Emitter)?
The time complexity for LeetCode 2694 (Event Emitter) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2694 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2694 in Java, C++, or Python.