Problem 421825 · hard · Level 04 Non-Linear Data Structures

Replay Stack of the Most Played Song

design · stack · hash map · frequency buckets · classes

A party jukebox keeps a pile of song requests. Design a class PlayStack:

  • PlayStack() starts empty.
  • push(song) adds one request for song (a string) to the pile.
  • pop() removes one request and returns its song: the song with the most requests currently in the pile; if several songs are tied, the one among them whose most recent request was pushed latest. The request removed is that song's most recent one still in the pile. If the pile is empty return "".

Examples

ops:  ["PlayStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop", "pop", "pop", "pop"]
args: [[], ["r"], ["s"], ["r"], ["s"], ["t"], ["s"], [], [], [], [], [], [], []]
Output: [None, None, None, None, None, None, None, "s", "s", "r", "t", "s", "r", ""]
Explanation: "s" has 3 requests and goes first. Then "r" and "s" both have 2 and "s"'s second request
(pushed 4th) is newer than "r"'s (pushed 3rd), so "s" goes again. Now "r" alone has 2. With one
request each, the latest-pushed requests win: t, then s, then r.

ops:  ["PlayStack", "push", "push", "push", "push", "pop", "pop", "pop", "pop"]
args: [[], ["x"], ["y"], ["y"], ["x"], [], [], [], []]
Output: [None, None, None, None, None, "x", "y", "y", "x"]
Explanation: the first pop removes x's newer request (pushed 4th) and the second y's (pushed 3rd).
Then x's remaining request was pushed 1st and y's 2nd, so y is newer and goes before x.

Constraints

  • Up to 2 * 10**4 calls in total; song names are short strings
  • Target: push and pop in O(1); searching all songs on every pop is too slow

Goals

  • Keep one stack per play count so the answer to pop is always on top of the highest stack
  • Maintain the current maximum count in O(1) per operation
Starting Python…