Extract the Quietest Log Tokens
Context
A document-monitoring service records each log token as an integer noise score. Analysts want the least noisy tokens for a compact report, but the archive can be large and the requested report may be small. Build a selector that keeps only the best candidates while reading the scores.
Problem
Write a function that selects the smallest k values from scores. Return the selected values in nondecreasing order. Each occurrence counts separately, so repeated scores must appear as many times as they were selected. If k is zero, return an empty array. If k is greater than the number of available scores, return every score, sorted in nondecreasing order. Process the input incrementally with a bounded max-heap: retain at most k candidates, and whenever a new score is smaller than the largest retained candidate, replace that largest candidate. This avoids sorting the entire input and keeps the retained state bounded by the requested selection size.
Examples
k = 3scores = [7, 2, 9, 2, 5][2, 2, 5]k = 0scores = [4, 1, 6][]k = 6scores = [8, 3, 3, 10][3, 3, 8, 10]Constraints
0 <= len(scores) <= 100000-1000000000 <= scores[i] <= 1000000000 for every i0 <= k <= len(scores) + 5- Types:
scoresis int[],kis int; result is int[]
Function signature
def select_quietest_tokens(scores: list[int], k: int) -> list[int]
scoreslist[int]- Integer noise scores recorded for the document's log tokens.
kint- The requested number of lowest scores to return.
- returns list[int]
- The min(k, len(scores)) lowest score occurrences, sorted from smallest to largest, with duplicates preserved.
Adapted from MBPP problem task_496 (CC BY 4.0). Rewritten, extended and verified by Iksha.
Notes
- A request larger than the available input is valid and returns all available values.
- Equal scores represent separate token occurrences and must not be deduplicated.