Problem 481764 · medium · Phase 04 Non-Linear Data Structures

Emergency Triage Stream

heaps · priority queue · stable ordering · streams

A clinic logs events in the order they happen. Each event is either

  • ["add", name, priority]: a patient arrives with an integer priority (higher = more urgent), or
  • ["serve"]: the doctor calls the most urgent waiting patient.

When several waiting patients share the highest priority, the one who arrived first is served. If nobody is waiting, a serve produces the string "none". The same name may appear more than once.

Return the list of names produced by the serve events, in order.

Examples

Input:  events = [["add", "ana", 2], ["add", "ben", 5], ["add", "cara", 2],
                  ["serve"], ["serve"], ["serve"], ["serve"]]
Output: ["ben", "ana", "cara", "none"]
Explanation: ben has the highest priority. ana and cara tie on 2, and ana arrived first.

Input:  events = [["serve"], ["add", "dan", 1], ["serve"], ["serve"]]
Output: ["none", "dan", "none"]

Constraints

  • 1 <= len(events) <= 10**5, 0 <= priority <= 10**9, names are non-empty strings
  • Target complexity: O(log n) per event, O(n log n) overall.

Goals

  • Process an interleaved stream of insertions and removals
  • Make a heap stable by attaching an arrival sequence number
  • Turn 'highest priority first' into a min-heap key
Starting Python…