Implement a Stock Price Tracker with the Observer Pattern

Quick Overview

Implement a stock price tracker where named subscribers follow stock symbols, receive price updates, and can read the last price they were notified about. It tests low-level design with the Observer pattern, picking a hash map layout for each lookup, and handling unsubscribe and missing-value cases correctly.

Implement a Stock Price Tracker with the Observer Pattern

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a simple stock price tracking system using the Observer pattern (also known as pub-sub). The system manages a set of stock symbols and allows named subscribers to register for price update notifications on specific stocks. When a stock's price is updated, all subscribers currently registered for that stock are notified, meaning their latest notified price for that stock is recorded. Subscribers can query the most recent price they were notified about for any stock. The system should support subscribing, unsubscribing, updating stock prices (which triggers notifications), querying a subscriber's latest notified price, counting subscribers for a stock, and retrieving the current price of a stock. Implement a class `StockPriceTracker` with the following methods: - `subscribe(subscriber: str, stock: str) -> None`: Subscribe a subscriber to receive notifications when the given stock's price is updated. - `unsubscribe(subscriber: str, stock: str) -> bool`: Unsubscribe a subscriber from a stock. Returns True if they were subscribed, False otherwise. - `updatePrice(stock: str, price: float) -> int`: Update the price of a stock and notify all current subscribers. Returns the number of subscribers notified. - `getNotifiedPrice(subscriber: str, stock: str) -> float`: Get the latest notified price for a given subscriber and stock. Returns -1.0 if the subscriber is not subscribed or has not been notified. - `getSubscriberCount(stock: str) -> int`: Get the number of current subscribers for a given stock symbol. - `getCurrentPrice(stock: str) -> float`: Get the current price of a stock. Returns -1.0 if the stock price has never been set. Example 1: ```text Input: ["StockPriceTracker", "getNotifiedPrice", "getCurrentPrice", "unsubscribe", "getSubscriberCount", "subscribe", "updatePrice", "getNotifiedPrice"] [[], ["alice", "TSLA"], ["TSLA"], ["alice", "TSLA"], ["TSLA"], ["alice", "TSLA"], ["TSLA", 250.5], ["alice", "TSLA"]] Output: [null, -1, -1, false, 0, null, 1, 250.5] Explanation: tracker = StockPriceTracker() # initialize tracker tracker.getNotifiedPrice("alice", "TSLA") # -> -1.0 (alice not subscribed) tracker.getCurrentPrice("TSLA") # -> -1.0 (TSLA price never set) tracker.unsubscribe("alice", "TSLA") # -> False (alice was not subscribed) tracker.getSubscriberCount("TSLA") # -> 0 (no subscribers) tracker.subscribe("alice", "TSLA") # alice subscribes to TSLA tracker.updatePrice("TSLA", 250.5) # -> 1 (notifies alice) tracker.getNotifiedPrice("alice", "TSLA") # -> 250.5 (alice was notified) ``` Example 2: ```text Input: ["StockPriceTracker", "subscribe", "subscribe", "updatePrice", "subscribe", "getNotifiedPrice", "unsubscribe", "getNotifiedPrice", "updatePrice", "getNotifiedPrice", "getSubscriberCount"] [[], ["bob", "AAPL"], ["carol", "AAPL"], ["AAPL", 190.0], ["dave", "AAPL"], ["dave", "AAPL"], ["bob", "AAPL"], ["bob", "AAPL"], ["AAPL", 191.25], ["dave", "AAPL"], ["AAPL"]] Output: [null, null, null, 2, null, -1, true, -1, 2, 191.25, 2] Explanation: tracker = StockPriceTracker() tracker.subscribe("bob", "AAPL") tracker.subscribe("carol", "AAPL") tracker.updatePrice("AAPL", 190.0) # -> 2 (notifies bob and carol) tracker.subscribe("dave", "AAPL") tracker.getNotifiedPrice("dave", "AAPL") # -> -1.0 (dave joined after the update) tracker.unsubscribe("bob", "AAPL") # -> True tracker.getNotifiedPrice("bob", "AAPL") # -> -1.0 (bob is no longer subscribed) tracker.updatePrice("AAPL", 191.25) # -> 2 (notifies carol and dave) tracker.getNotifiedPrice("dave", "AAPL") # -> 191.25 tracker.getSubscriberCount("AAPL") # -> 2 ``` ```hint Two lookup directions updatePrice needs every subscriber of one stock, and getNotifiedPrice needs one subscriber's price for one stock. Decide which structure answers each call without a scan. ``` ```hint The -1.0 cases List every situation in which getNotifiedPrice must return -1.0, including what should happen to a stored price when its subscriber leaves. ``` ### Constraints & Assumptions - `1 <= length of stock symbol <= 10` - Stock symbols consist of uppercase English letters only. - `0.0 <= price <= 10^5` - Subscriber names consist of lowercase English letters and digits. - `1 <= length of subscriber name <= 20` - At most `10^4` total operations. ### Clarifying Questions to Ask - Do stock symbols need to be registered before use, or does a symbol exist as soon as someone subscribes to it or sets its price? - If a subscriber calls subscribe twice for the same stock, should they be counted and notified once? - Should a subscriber who joins after a price update receive the current price right away, or only on the next update? - Is the tracker called from a single thread, or must subscriptions and price updates be safe under concurrent calls? ### What a Strong Answer Covers - A data model that answers each method directly, with the time cost of every method stated. - How the design maps onto the Observer pattern (subject, observer, attach, detach, notify), and how it changes when subscribers are objects with a callback. - Correct results for the sentinel cases: an unknown stock, an unknown subscriber, a subscriber who joined after the last update, and an unsubscribe for someone who was not subscribed. - What unsubscribe does to the subscriber's stored price, and why the -1.0 rule requires it. - How memory grows with the number of subscriptions. ### Follow-up Questions - If each subscriber is an object with a callback, and a callback may unsubscribe itself while notifications are going out, what has to change in updatePrice? - How would you make the tracker safe when several threads publish prices and change subscriptions at the same time? - One stock has a million subscribers and some of them are slow. How do you keep updatePrice from blocking the publisher? - How would you support subscribers who only want a notification when the price moves by more than a set percentage?

Overview: Implement a stock price tracker where named subscribers follow stock symbols, receive price updates, and can read the last price they were notified about. It tests low-level design with the Observer pattern, picking a hash map layout for each lookup, and handling unsubscribe and missing-value cases correctly.

General logo
General
Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a simple stock price tracking system using the Observer pattern (also known as pub-sub). The system manages a set of stock symbols and allows named subscribers to register for price update notifications on specific stocks.

When a stock's price is updated, all subscribers currently registered for that stock are notified, meaning their latest notified price for that stock is recorded. Subscribers can query the most recent price they were notified about for any stock.

The system should support subscribing, unsubscribing, updating stock prices (which triggers notifications), querying a subscriber's latest notified price, counting subscribers for a stock, and retrieving the current price of a stock.

Implement a class StockPriceTracker with the following methods:

  • subscribe(subscriber: str, stock: str) -> None : Subscribe a subscriber to receive notifications when the given stock's price is updated.
  • unsubscribe(subscriber: str, stock: str) -> bool : Unsubscribe a subscriber from a stock. Returns True if they were subscribed, False otherwise.
  • updatePrice(stock: str, price: float) -> int : Update the price of a stock and notify all current subscribers. Returns the number of subscribers notified.
  • getNotifiedPrice(subscriber: str, stock: str) -> float : Get the latest notified price for a given subscriber and stock. Returns -1.0 if the subscriber is not subscribed or has not been notified.
  • getSubscriberCount(stock: str) -> int : Get the number of current subscribers for a given stock symbol.
  • getCurrentPrice(stock: str) -> float : Get the current price of a stock. Returns -1.0 if the stock price has never been set.

Example 1:

Input:
["StockPriceTracker", "getNotifiedPrice", "getCurrentPrice", "unsubscribe",     "getSubscriberCount", "subscribe",       "updatePrice",   "getNotifiedPrice"]
[[],                  ["alice", "TSLA"],  ["TSLA"],          ["alice", "TSLA"], ["TSLA"],             ["alice", "TSLA"], ["TSLA", 250.5], ["alice", "TSLA"]]

Output: [null, -1, -1, false, 0, null, 1, 250.5]

Explanation:
tracker = StockPriceTracker()              # initialize tracker
tracker.getNotifiedPrice("alice", "TSLA")  # -> -1.0  (alice not subscribed)
tracker.getCurrentPrice("TSLA")            # -> -1.0  (TSLA price never set)
tracker.unsubscribe("alice", "TSLA")       # -> False (alice was not subscribed)
tracker.getSubscriberCount("TSLA")         # -> 0     (no subscribers)
tracker.subscribe("alice", "TSLA")         # alice subscribes to TSLA
tracker.updatePrice("TSLA", 250.5)         # -> 1     (notifies alice)
tracker.getNotifiedPrice("alice", "TSLA")  # -> 250.5 (alice was notified)

Example 2:

Input:
["StockPriceTracker", "subscribe", "subscribe", "updatePrice", "subscribe", "getNotifiedPrice", "unsubscribe", "getNotifiedPrice", "updatePrice", "getNotifiedPrice", "getSubscriberCount"]
[[], ["bob", "AAPL"], ["carol", "AAPL"], ["AAPL", 190.0], ["dave", "AAPL"], ["dave", "AAPL"], ["bob", "AAPL"], ["bob", "AAPL"], ["AAPL", 191.25], ["dave", "AAPL"], ["AAPL"]]

Output: [null, null, null, 2, null, -1, true, -1, 2, 191.25, 2]

Explanation:
tracker = StockPriceTracker()
tracker.subscribe("bob", "AAPL")
tracker.subscribe("carol", "AAPL")
tracker.updatePrice("AAPL", 190.0)         # -> 2      (notifies bob and carol)
tracker.subscribe("dave", "AAPL")
tracker.getNotifiedPrice("dave", "AAPL")   # -> -1.0   (dave joined after the update)
tracker.unsubscribe("bob", "AAPL")         # -> True
tracker.getNotifiedPrice("bob", "AAPL")    # -> -1.0   (bob is no longer subscribed)
tracker.updatePrice("AAPL", 191.25)        # -> 2      (notifies carol and dave)
tracker.getNotifiedPrice("dave", "AAPL")   # -> 191.25
tracker.getSubscriberCount("AAPL")         # -> 2

Constraints & Assumptions

  • 1 <= length of stock symbol <= 10
  • Stock symbols consist of uppercase English letters only.
  • 0.0 <= price <= 10^5
  • Subscriber names consist of lowercase English letters and digits.
  • 1 <= length of subscriber name <= 20
  • At most 10^4 total operations.

Clarifying Questions to Ask Guidance

  • Do stock symbols need to be registered before use, or does a symbol exist as soon as someone subscribes to it or sets its price?
  • If a subscriber calls subscribe twice for the same stock, should they be counted and notified once?
  • Should a subscriber who joins after a price update receive the current price right away, or only on the next update?
  • Is the tracker called from a single thread, or must subscriptions and price updates be safe under concurrent calls?

What a Strong Answer Covers Guidance

  • A data model that answers each method directly, with the time cost of every method stated.
  • How the design maps onto the Observer pattern (subject, observer, attach, detach, notify), and how it changes when subscribers are objects with a callback.
  • Correct results for the sentinel cases: an unknown stock, an unknown subscriber, a subscriber who joined after the last update, and an unsubscribe for someone who was not subscribed.
  • What unsubscribe does to the subscriber's stored price, and why the -1.0 rule requires it.
  • How memory grows with the number of subscriptions.

Follow-up Questions Guidance

  • If each subscriber is an object with a callback, and a callback may unsubscribe itself while notifications are going out, what has to change in updatePrice?
  • How would you make the tracker safe when several threads publish prices and change subscriptions at the same time?
  • One stock has a million subscribers and some of them are slow. How do you keep updatePrice from blocking the publisher?
  • How would you support subscribers who only want a notification when the price moves by more than a set percentage?