Design a topic notification system with the Observer pattern
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design an in-memory notification system using the Observer pattern. The system manages named topics (channels) that users can subscribe to. When a message is published to a topic, every current subscriber of that topic receives a notification.
Users can subscribe to several topics, unsubscribe from topics, and read the notifications they received in chronological order. If a user subscribes to the same topic more than once, only one subscription is kept.
A notification delivered to a user is the string `[topic] message`. Publishing to a topic with no subscribers notifies zero users. Unsubscribing from a topic the user is not subscribed to returns `False`.
Implement a class `NotificationSystem` with these methods:
- `subscribe(user: str, topic: str) -> None`: subscribe the user to the topic. If the user is already subscribed, do nothing.
- `unsubscribe(user: str, topic: str) -> bool`: remove the subscription. Return `True` if the user was subscribed, `False` otherwise.
- `publish(topic: str, message: str) -> int`: send `[topic] message` to every current subscriber of the topic and return the number of users notified.
- `getNotifications(user: str) -> List[str]`: return all notifications the user has received, in chronological order.
- `getNotificationCount(user: str) -> int`: return the total number of notifications the user has received.
- `getSubscribers(topic: str) -> List[str]`: return the current subscribers of the topic as a sorted list.
- `clearNotifications(user: str) -> int`: clear all of the user's notifications and return how many were cleared.
Example 1:
```text
operations = ["NotificationSystem", "subscribe", "subscribe", "subscribe", "publish",
"getNotifications", "getNotifications", "unsubscribe", "publish",
"getNotifications", "getNotifications"]
arguments = [[], ["Alice", "Sports"], ["Bob", "Sports"], ["Alice", "Tech"],
["Sports", "Goal scored!"], ["Alice"], ["Bob"], ["Bob", "Sports"],
["Sports", "Match over"], ["Alice"], ["Bob"]]
Output: [null, null, null, null, 2, ["[Sports] Goal scored!"], ["[Sports] Goal scored!"],
true, 1, ["[Sports] Goal scored!", "[Sports] Match over"], ["[Sports] Goal scored!"]]
```
Alice subscribes to Sports and Tech, and Bob subscribes to Sports. Publishing "Goal scored!" to Sports notifies both of them, so `publish` returns 2. After Bob unsubscribes, "Match over" reaches only Alice. Bob keeps the notification he already received.
Example 2:
```text
operations = ["NotificationSystem", "publish", "subscribe", "unsubscribe", "subscribe",
"publish", "getNotifications", "getNotificationCount", "clearNotifications",
"getNotifications"]
arguments = [[], ["News", "Breaking!"], ["Charlie", "News"], ["Charlie", "Sports"],
["Charlie", "News"], ["News", "Update"], ["Charlie"], ["Charlie"],
["Charlie"], ["Charlie"]]
Output: [null, 0, null, false, null, 1, ["[News] Update"], 1, 1, []]
```
Publishing to News before anyone subscribes returns 0. Charlie then subscribes to News. Unsubscribing him from Sports returns `False` because he never subscribed to it, and his second News subscription changes nothing. Publishing "Update" notifies Charlie once, and after `clearNotifications` returns 1 his list is empty.
```hint Assign the roles
Decide which class is the subject and which is the observer, and what the single notify call passes along.
```
```hint Choose containers for the edge cases
Pick a structure for each topic's subscribers that makes a repeated subscribe harmless and tells you whether an unsubscribe removed anything.
```
### Constraints & Assumptions
- Topic and user names are 1 to 50 characters long.
- Messages are 1 to 200 characters long.
- At most 10,000 operations are performed in total.
- Names and messages contain letters, digits, spaces and basic punctuation.
### Clarifying Questions to Ask
- What should the query methods return for a user name that has never subscribed or received anything?
- After `clearNotifications`, should `getNotificationCount` still count the cleared notifications, or only the ones currently stored?
- Does a user who subscribes to a topic see messages published before they joined?
- Is the system called from a single thread, or can publishes and subscriptions happen concurrently?
### What a Strong Answer Covers
- A clear mapping of the Observer roles: which class is the subject, which is the observer, and what the update call carries.
- Data structures that keep one subscription per user and topic, make subscribe and unsubscribe constant time, and keep each user's notifications in arrival order.
- Correct results for the edge cases in the spec: an unknown or empty topic, an unsubscribe with no subscription, a repeated subscribe, and a user who has received nothing.
- Time and space complexity for each method, including what `getSubscribers` pays for sorting.
- Encapsulation: notifications stay with a user after they unsubscribe, and getters return copies so callers cannot change internal state.
### Follow-up Questions
- How would you make the system safe to call from many threads at once, and what would you lock?
- How would you add email or push delivery without changing the topic class?
- If a topic has a million subscribers, how would you avoid storing a million copies of each message?
- How would you let a new subscriber replay the last N messages of a topic?
Overview: Design an in-memory notification system with the Observer pattern, where users subscribe to named topics, receive formatted messages when a topic publishes, and read or clear their notifications in order. It tests object-oriented design, choice of data structures, edge-case handling and per-method complexity.