KatInterview

Build an In-Memory Playlist Engine with a Three-Slot Favorites Set

Data Structure DesignModel answer
MediumModel answerData Structure Designdesigndequehash-map

Last 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() or prev() 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

  1. The class implementation.
  2. The data structures you chose and why.
  3. Time and space complexity for each operation.
  4. 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.