Risk-Ranked Alert Queue Simulator
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a priority queue of alerts that serves the highest risk first and the oldest first on ties, driven by a list of Put and GetNext commands.
You are building the core of an alert-triage queue. Each alert has three string fields: an identifier, a risk score, and a payload. Alerts are fed in one at a time, and whenever the analyst asks for work, the queue hands out the most urgent alert and removes it.
Rather than building a class, you will simulate the queue. You are given a list of commands and a parallel list of their arguments. Process the commands in order and return one result per command.
Commands
"Put": the arguments are[alert_id, risk_score, payload]. Add the alert to the queue. The result for this command isNone."GetNext": the arguments are an empty list. Remove the most urgent alert from the queue and return it as[alert_id, risk_score, payload], with all three values as strings. If the queue is empty, the result isNoneand nothing changes.
Ordering rules
- The alert with the highest risk score is served first.
- Among alerts with the same risk score, the one that was added earliest (by its
Putorder) is served first. - Risk scores are non-negative integers written as decimal strings. Compare them as numbers, not as text. They can be as large as an unsigned 64-bit integer (up to
18446744073709551615). - When an alert is returned, its score is written in canonical decimal form, so a score given as
"007"is returned as"7".
Duplicate identifiers
Identifiers are not checked for uniqueness. If Put is called with an alert_id that is already in the queue, it is simply a separate alert. Nothing is replaced, merged, or rejected, and each copy is served according to its own score and arrival order.
Input and output
commands[i]is either"Put"or"GetNext", andarguments[i]holds the arguments for that command.- Return a list of the same length as
commands. EntryiisNonefor everyPutand for aGetNexton an empty queue, and otherwise a list of three strings.
Constraints
len(commands) == len(arguments).- Every command is either
"Put"or"GetNext". - For
"Put",arguments[i]has exactly three strings. The second is a non-negative integer in decimal form, at most2^64 - 1. - For
"GetNext",arguments[i]is an empty list. - Aim for
O(log n)time per command, wherenis the number of alerts currently queued.
Examples
Example 1
Input: risk_queue_simulation(['Put', 'Put', 'GetNext', 'GetNext', 'GetNext'], [['det-1', '5', 'alert'], ['det-2', '9', 'malware'], [], [], []])
Output: [None, None, ['det-2', '9', 'malware'], ['det-1', '5', 'alert'], None]
Example 2
Input: risk_queue_simulation(['Put', 'Put', 'GetNext', 'GetNext'], [['low', '2', 'a'], ['high', '7', 'b'], [], []])
Output: [None, None, ['high', '7', 'b'], ['low', '2', 'a']]
Hints
Hint 1
Which standard data structure gives you the best element in logarithmic time while still allowing insertions?
Hint 2
Python's heapq is a min-heap. Think about how to make the highest score come out first, and how to make the earliest insertion win among equal scores.
Hint 3
Convert the score to an int before comparing, so ordering is numeric. Add an increasing counter to each entry as a tie-breaker, so you never compare ids or payloads.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a binary heap, which suits "repeatedly take the best element while new ones keep arriving".
- Python's
heapqis a min-heap, so each alert is stored as the tuple(-score, counter, alert_id, payload).- Negating the integer score makes the highest score the smallest key.
counteris a number that increases with everyPut. Among equal scores, the smaller counter (earlier arrival) is popped first.- Because
counteris unique, tuple comparison never reachesalert_idorpayload. Duplicate ids therefore need no special handling, and each copy is its own entry.
Putpushes a tuple and appendsNoneto the results.GetNextpops the smallest tuple if the heap is non-empty, undoes the negation, and appends[alert_id, str(score), payload]. If the heap is empty, it appendsNone.
Scores are parsed with int(...), so ordering is numeric, even for values near 2^64 - 1 (Python integers do not overflow). Printing with str gives the canonical form without leading zeros.
Why it is correct
The heap always exposes the entry with the smallest (-score, counter). That is exactly the highest score, with the earliest insertion breaking ties, which is the required serving order. Every pop removes that entry, so the next one is again the best of the remainder.
Complexity
- Time:
O(log n)perPutand perGetNext, wherenis the number of queued alerts. Total time isO(m log n)formcommands. - Space:
O(n)for the heap, plusO(m)for the results.
Reference solution
from typing import List, Optional
import heapq
def risk_queue_simulation(commands: List[str], arguments: List[List[str]]) -> List[Optional[List[str]]]:
heap = []
results = []
counter = 0
for command, args in zip(commands, arguments):
if command == "Put":
alert_id, risk_score, payload = args
heapq.heappush(heap, (-int(risk_score), counter, alert_id, payload))
counter += 1
results.append(None)
elif command == "GetNext":
if heap:
neg_score, _, alert_id, payload = heapq.heappop(heap)
results.append([alert_id, str(-neg_score), payload])
else:
results.append(None)
else:
raise ValueError("unknown command")
return results