#2694

Event Emitter

Medium
Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal approach, we maintain a dictionary to store events and their callbacks, allowing for efficient subscription and emission. This structure allows us to quickly access and manage the callbacks associated with each event.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a dictionary to hold events and their corresponding callbacks.
  2. 2Step 2: In the subscribe method, add the callback to the list of callbacks for the specified event.
  3. 3Step 3: In the emit method, retrieve the callbacks for the event and execute them, collecting the results in an array.
solution.py14 lines
1class EventEmitter:
2    def __init__(self):
3        self.events = {}
4
5    def subscribe(self, event, callback):
6        if event not in self.events:
7            self.events[event] = []
8        self.events[event].append(callback)
9        return {'unsubscribe': lambda: self.events[event].remove(callback)}
10
11    def emit(self, event, *args):
12        if event not in self.events:
13            return []
14        return [callback(*args) for callback in self.events[event]]

Complexity note: The time complexity is O(n) for emitting events because we only iterate through the list of callbacks once. The space complexity remains O(n) due to storing the callbacks.

  • 1Understanding how to manage subscriptions and emissions efficiently is crucial.
  • 2Recognizing that events can have multiple callbacks helps in designing the data structure.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.