PracticeData Structures

Extract the Quietest Log Tokens

MediumData Structurestraversalstate trackinginvariants Time not estimated Not started

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

Example 1
Input: k = 3scores = [7, 2, 9, 2, 5]
Output: [2, 2, 5]
Explanation: For scores [7, 2, 9, 2, 5] with k equal to 3, execution returns [2, 2, 5], including two occurrences of 2.
Example 2
Input: k = 0scores = [4, 1, 6]
Output: []
Explanation: For scores [4, 1, 6] with k equal to 0, execution returns an empty array.
Example 3
Input: k = 6scores = [8, 3, 3, 10]
Output: [3, 3, 8, 10]
Explanation: Because k equal to 6 exceeds the four available scores, execution returns every score in nondecreasing order as [3, 3, 8, 10]. (,, )

Constraints

  • 0 <= len(scores) <= 100000
  • -1000000000 <= scores[i] <= 1000000000 for every i
  • 0 <= k <= len(scores) + 5
  • Types: scores is int[], k is int; result is int[]

Function signature

def select_quietest_tokens(scores: list[int], k: int) -> list[int]
scores list[int]
Integer noise scores recorded for the document's log tokens.
k int
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.
Approved · cb001-abs_950_v314 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1