Scored Catalog Rotator: Ordered Traversal with Live Updates
Data Structure DesignModel answerLast updated
Design an in-memory playlist that always serves the highest-scored unseen item per round, supports live score changes, and is safe for concurrent callers.
Scored Catalog Rotator
You are building an in-memory content rotator. Every item in the catalog has a numeric score, and that score can change at any moment. The rotator hands out items one at a time through a get() call, enforcing a fairness rule: every item must be served exactly once before any item can be served again.
More precisely:
- Each call to
get()returns exactly one item — the one with the highest score among those not yet served in the current round. - When every item has been served, the round resets. The very next
get()begins a fresh round in which all items are available again. update_score(item_id, score)changes the score of an existing item. If theitem_idis new, the item is added to the catalog.
Score updates can arrive at any time, including in the middle of a round.
Constraints and clarifications
- The full catalog fits in memory on a single machine. Item IDs are unique.
- No upper bound on catalog size is given; express complexity in terms of n, the number of items in the catalog.
- You may define reasonable tie-breaking behavior — just state it explicitly.
- Clarify what happens in each of these cases and code accordingly:
- A not-yet-served item's score changes mid-round.
- An already-served item's score changes mid-round.
- A brand-new item is added mid-round.
get()is called on an empty catalog.
Part 1 — Core implementation
Implement:
class CatalogRotator:
def update_score(self, item_id: str, score: float) -> None: ...
def get(self) -> str | None: ...
State the time and space complexity of each operation, including the cost of the round-reset that happens inside get() when a round ends.
What your answer should address:
- Which data structures you chose and why — specifically how they support highest-score extraction, arbitrary score updates, and round rollover together.
- Explicit rules for ties and for score updates that arrive mid-round.
- Big-O for
update_score,getin the steady case, andgetat the moment of rollover.
Part 2 — Concurrent callers
Multiple threads now call get() and update_score() concurrently.
- Identify which operations are read-modify-write and must execute atomically.
- Describe where you place locks and at what granularity.
- Discuss the trade-off between a single coarse lock and finer-grained alternatives.
- What invariants must hold even under concurrent access?
Hints
Hint 1
Think about what data you need to maintain in two separate states: items still available this round versus items already served. A sorted structure for the available set lets you extract the max efficiently without a full scan.
Hint 2
A heap alone makes score updates expensive (you can't find an arbitrary element in O(log n)). A sorted map keyed by (score, item_id) combined with a plain hash map gives you O(log n) lookup, removal, and insertion together.
Hint 3
For concurrency, list every piece of shared mutable state — the sorted available set, the served set, and the scores map — then ask: which sequences of reads and writes produce an inconsistent result if interrupted? That tells you the minimum critical sections you need to protect.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and design decisions
Clarifying the semantics first
Before touching code, nail down the four mid-round edge cases:
| Situation | Rule |
|---|---|
| Not-yet-served item gets a new score | New score takes effect immediately; it repositions in the available set for this round. |
| Already-served item gets a new score | New score is stored but only affects ordering in the next round (item is not re-served). |
| Brand-new item added mid-round | Treat it like a not-yet-served item; it enters the current round's available set. |
get() on an empty catalog | Return None. |
Stating these up front prevents ambiguity and makes the code's invariants obvious to a reviewer.
Ties: break by item_id lexicographically (ascending), so behavior is deterministic and testable.
Data structures
The core tension is: you need O(log n) max-extraction and O(log n) arbitrary-score updates. A plain max-heap fails the second requirement because finding an element by ID is O(n).
Use three structures:
scores: dict[str, float]— maps item_id to current score. O(1) lookup and update.available: SortedList(or a balanced BST /SortedListfromsortedcontainers) keyed by(-score, item_id)— the items not yet served this round, ordered so the minimum key corresponds to the highest score.served: set[str]— item IDs already handed out this round.
In Python sortedcontainers.SortedList gives O(log n) add/remove and O(1) access to the minimum element. In Java you'd use a TreeMap<double[], String> or a TreeSet with a custom comparator. In Go, a third-party treap or a skip-list serves the same role.
Implementation
from sortedcontainers import SortedList
class CatalogRotator:
def __init__(self):
self._scores: dict[str, float] = {}
# Key: (-score, item_id) so smallest key = highest score
self._available: SortedList = SortedList(key=lambda x: (x[0], x[1]))
self._served: set[str] = set()
def update_score(self, item_id: str, score: float) -> None:
if item_id in self._scores:
old_score = self._scores[item_id]
# Only reposition if the item is still available this round
if item_id not in self._served:
self._available.remove((-old_score, item_id))
self._available.add((-score, item_id))
else:
# New item enters the current round's available set
self._available.add((-score, item_id))
self._scores[item_id] = score
def get(self) -> str | None:
if not self._scores:
return None
# Rollover: every item has been served, start a new round
if not self._available:
self._served.clear()
for item_id, score in self._scores.items():
self._available.add((-score, item_id))
# Still nothing after rollover means catalog is empty (already guarded above)
neg_score, item_id = self._available.pop(0)
self._served.add(item_id)
return item_id
Complexity
| Operation | Time | Notes |
|---|---|---|
update_score (existing, available) | O(log n) | One remove + one insert into sorted list |
update_score (existing, served) | O(1) | Only the dict is updated |
update_score (new item) | O(log n) | One insert |
get (steady state) | O(log n) | pop(0) on a sorted list |
get at rollover | O(n log n) | Rebuilding the available set; amortized over n calls → O(log n) per call |
Space: O(n) across all three structures.
Part 2 — Concurrency
What shared state exists: _scores, _available, and _served are all mutated by both get and update_score. Without synchronization, the following races are possible:
- Two threads both see
_availableas empty, both trigger rollover, and double-insert every item. - One thread reads
item_id not in self._servedwhile another thread is mid-way throughget, which removes the item from_availableafter the check but before the remove call. pop(0)and a concurrentremoveinsideupdate_scoreoperating on_availablesimultaneously corrupt the sorted list.
Simple correct solution — one coarse lock:
import threading
class CatalogRotatorThreadSafe(CatalogRotator):
def __init__(self):
super().__init__()
self._lock = threading.Lock()
def update_score(self, item_id: str, score: float) -> None:
with self._lock:
super().update_score(item_id, score)
def get(self) -> str | None:
with self._lock:
return super().get()
This is correct and the right answer for an interview. Every operation is short and CPU-bound, so lock contention is unlikely to be the bottleneck in practice.
Where finer granularity helps (and where it doesn't):
A reader-writer lock helps only if there are meaningful read-only operations. Both get and update_score mutate state, so a RWLock buys nothing here — all callers take the write lock.
One genuine optimization: decouple score storage from the ordering structure. A ConcurrentHashMap for scores allows lock-free reads, while a separate lock guards _available and _served. This reduces contention only when update_score for a served item is very frequent, since that path touches only the dict. For most workloads the single lock is simpler and fast enough.
Invariants that must hold under concurrency:
- An item never appears in both
_availableand_servedat the same time. - Rollover (clearing
_servedand rebuilding_available) is atomic — no partial state is visible to other threads. - Each item is served exactly once per round, regardless of how many threads call
get()simultaneously.
Common mistakes to avoid
- Using a heap and doing lazy-deletion: it works but requires careful bookkeeping of "stale" entries and is easy to get wrong under score updates mid-round.
- Forgetting that rollover itself is a read-modify-write on
_servedand_available— it must be inside the same critical section as thepop. - Applying the new score to the current round for already-served items, which would violate the "served at most once per round" invariant.
- Returning a random item on tie instead of something deterministic — makes the system hard to test.