00:00

Problem Statement

Input/Output Examples

Visual Explanation

The publisher and the listeners only share the topic name and the event data, which is what makes the design easy to extend.

Approaches

Both approaches deliver events in subscription order. The first indexes listeners by topic; the second keeps one list of subscriptions.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

With the map, a publish costs one call per listener of that topic. With a single list, a publish scans every subscription.

Interview Tips and Recommended Approach

  • Name the pattern: observer, also called publish/subscribe when a broker sits in the middle.
  • Return an unsubscribe handle. Listeners that are never removed are a classic memory leak.
  • Decide what happens when a listener throws. Usually log it and continue with the others.
  • Mention async delivery. Running listeners on an executor stops a slow one from blocking the publisher.

Recommended Approach: Map of Topic to Listeners

Why: publishing only touches the right listeners, and the concurrent collections make the bus thread-safe with almost no code.