Build an In-Memory Playlist Engine with a Three-Slot Favorites Set
Data Structure DesignModel answerLast updated
Design a thread-safe in-memory audio player with a queue, history, and a favorites list capped at three that rejects overflow deterministically rather than evicting.
Build an in-memory audio player class. It has no persistence and no real audio, only state management.
Library and playback operations
addSong(id, metadata): register a track.removeSong(id): delete a track from the library.play(id): start the given track.pause(): pause the current track.next()/prev(): move forward or backward through playback.getNowPlaying(): report the current track.queueSong(id): append a track to the upcoming queue.
Favorites operations
The player keeps a favorites list with a fixed capacity of 3.
addFavorite(id)removeFavorite(id)listFavorites()
Do not use an LRU-style cache. When a caller tries to add a fourth favorite, the behavior must be deterministic and documented (for example, reject the request with an error) rather than silently evicting something.
Edge cases you must decide on and handle
- Removing the track that is currently playing.
- Adding the same song or the same favorite twice.
- Calling
next()orprev()when there is nothing to move to. - Operations that receive an unknown song id.
- Several threads calling the API at the same time.
What to deliver
- The class implementation.
- The data structures you chose and why.
- Time and space complexity for each operation.
- A set of unit tests covering the edge cases above.
State your behavioral contract explicitly before writing code, because the problem leaves several choices open.
Hints
Hint 1
Split the state into independent pieces (library, upcoming queue, played history, current track and play state, favorites) and choose the cheapest structure for each. Ends-only access suggests a double-ended queue.
Hint 2
Write down a contract for every ambiguous case first: what do duplicates, unknown ids, empty navigation and a full favorites list do? Prefer explicit errors or a boolean result over silent side effects.
Hint 3
Define two invariants: every id referenced anywhere exists in the library, and favorites never exceed 3. Then make removal purge the id everywhere, and guard every public method with a single re-entrant lock so the size check and insert are atomic.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat this as a state-management problem. Decide a structure per piece of state, write the behavior contract for each edge case, then enforce two invariants under a lock.
State and data structures
| State | Structure | Reason |
|---|---|---|
| Library | dict[id -> metadata] | O(1) add, lookup, remove |
| Upcoming queue | deque | O(1) pop from the front for next(), O(1) push to the front for prev() |
| History | bounded deque | Works like a stack for prev(); maxlen caps memory |
| Current track | id plus state (STOPPED, PLAYING, PAUSED) | One source of truth |
| Favorites | insertion-ordered dict used as an ordered set | O(1) membership, stable listing order, no eviction |
Behavioral contract
addSong: a duplicate id raisesDuplicateSongError. Silent overwrite hides bugs.- Unknown id in
removeSong,play,queueSong,addFavorite: raiseSongNotFoundError. play(id): if another track was current, push it onto history, then makeidcurrent andPLAYING. Playing the current id again just resumes and leaves history alone.pause(): switchesPLAYINGtoPAUSEDand returnsTrue; otherwise returnsFalse.next(): if the queue is empty, returnNonewith no state change. Otherwise push the current track to history and pop the queue front into current.prev(): if history is empty, returnNonewith no change. Otherwise push the current track to the front of the queue (sonext()undoesprev()) and pop history into current.removeSongon the playing track: stop playback (current = None,STOPPED) and do not auto-advance. Purge the id from queue, history and favorites. Auto-advance is a valid alternative if documented.- Favorites: adding an existing favorite is idempotent and returns
False. Adding a fourth raisesFavoritesFullError; the caller must remove one first. Removing a non-favorite returnsFalse. - Duplicates in the queue are allowed, as in real players.
- Concurrency: every public method takes one
threading.RLock. Readers return copies.
Why it is correct
Two invariants hold after every operation:
- Every id in the queue, history, favorites and current slot exists in the library. Every insertion validates the id, and
removeSongpurges all structures before deleting from the library. - Favorites hold at most 3 ids. The size check and the insert occur in one critical section. Without the lock, two threads could both observe size 2 and both insert, producing 4.
next and prev mirror each other: each moves the current track onto the opposite structure, so alternating them walks back and forth without losing tracks.
Complexity
| Operation | Time |
|---|---|
addSong, play, pause, getNowPlaying, queueSong | O(1) |
next, prev | O(1) |
removeSong | O(Q + H) because of the eager purge |
addFavorite, removeFavorite, listFavorites | O(1) since the cap is the constant 3 |
Space is O(N + Q + H); history is bounded by maxlen.
Trade-off: lazy deletion (skip dead ids when popping) makes removeSong O(1), but a later re-add of the same id would revive stale entries. Eager purge is simpler to reason about, so use it unless removal is hot.
Code
import threading
from collections import deque
from enum import Enum
class SongNotFoundError(KeyError): pass
class DuplicateSongError(ValueError): pass
class FavoritesFullError(RuntimeError): pass
class State(Enum):
STOPPED = "stopped"
PLAYING = "playing"
PAUSED = "paused"
class MusicPlayer:
FAVORITES_CAP = 3
def __init__(self, history_limit=1000):
self._lock = threading.RLock()
self._library = {}
self._queue = deque()
self._history = deque(maxlen=history_limit)
self._current = None
self._state = State.STOPPED
self._favorites = {}
def _require(self, sid):
if sid not in self._library:
raise SongNotFoundError(sid)
def addSong(self, sid, metadata):
with self._lock:
if sid in self._library:
raise DuplicateSongError(sid)
self._library[sid] = dict(metadata)
def removeSong(self, sid):
with self._lock:
self._require(sid)
if self._current == sid:
self._current, self._state = None, State.STOPPED
self._queue = deque(s for s in self._queue if s != sid)
self._history = deque((s for s in self._history if s != sid),
maxlen=self._history.maxlen)
self._favorites.pop(sid, None)
del self._library[sid]
def queueSong(self, sid):
with self._lock:
self._require(sid)
self._queue.append(sid)
def play(self, sid):
with self._lock:
self._require(sid)
if sid == self._current:
self._state = State.PLAYING
return sid
if self._current is not None:
self._history.append(self._current)
self._current, self._state = sid, State.PLAYING
return sid
def pause(self):
with self._lock:
if self._state is State.PLAYING:
self._state = State.PAUSED
return True
return False
def next(self):
with self._lock:
if not self._queue:
return None
if self._current is not None:
self._history.append(self._current)
self._current = self._queue.popleft()
self._state = State.PLAYING
return self._current
def prev(self):
with self._lock:
if not self._history:
return None
if self._current is not None:
self._queue.appendleft(self._current)
self._current = self._history.pop()
self._state = State.PLAYING
return self._current
def getNowPlaying(self):
with self._lock:
return self._current
def addFavorite(self, sid):
with self._lock:
self._require(sid)
if sid in self._favorites:
return False
if len(self._favorites) >= self.FAVORITES_CAP:
raise FavoritesFullError(sid)
self._favorites[sid] = True
return True
def removeFavorite(self, sid):
with self._lock:
return self._favorites.pop(sid, None) is not None
def listFavorites(self):
with self._lock:
return list(self._favorites)
Tests to include
- Add a duplicate song raises; unknown ids raise in every method that takes one.
- Add three favorites, the fourth raises, remove one, then the fourth succeeds.
- Re-adding a favorite returns
Falseand leaves the list unchanged. next()on an empty queue andprev()on empty history returnNoneand change nothing.next()thenprev()returns to the original track.- Removing the playing track yields
getNowPlaying() is Noneand no references remain in queue, history or favorites. - Concurrency: 50 threads calling
addFavoriteon distinct songs always leaves exactly 3 favorites.
Common mistakes
- Using an LRU structure and silently evicting favorites.
- Forgetting to purge a removed song from favorites or history, leaving dangling ids.
- Doing the favorites size check outside the lock.
- Using a plain
Lockand deadlocking when one public method calls another. - Returning internal containers so callers can mutate state.
- Leaving the behavior on ambiguous cases undefined instead of stating it.