Rebuild a Document's Token Index
Context
A document archive stores the tokens from each note in the order they were captured. For an index-building step, the archive needs those tokens arranged alphabetically. Repeated words must remain repeated because their counts are meaningful. Create the ordered token stream using a priority queue rather than assuming the captured order is useful.
Problem
Write a function that receives the token list from one document and returns a new list containing the same tokens in nondecreasing lexicographic order. Every occurrence must be retained, including repeated tokens. The input may be empty, already ordered, reversed, or arranged unpredictably. Build a min-heap of pending tokens, then repeatedly remove its smallest token until no pending tokens remain. Do not change the input list.
Examples
tokens = [][]tokens = ["apple", "banana", "banana", "cherry"]["apple", "banana", "banana", "cherry"]tokens = ["pear", "apple", "orange", "apple", "grape"]["apple", "apple", "grape", "orange", "pear"]Constraints
0 <= len(tokens) <= 1000001 <= len(tokens[i]) <= 30 for every itokens[i]: alphabet lowercaseTokens contain lowercase English letters only.- Types:
tokensis str[]; result is str[]
Function signature
def order_document_tokens(tokens: list[str]) -> list[str]
tokenslist[str]- The captured tokens from one document, possibly empty and possibly containing repeated words.
- returns list[str]
- A new list containing exactly the input tokens, arranged in nondecreasing lexicographic order.
Adapted from MBPP problem task_635 (CC BY 4.0). Rewritten, extended and verified by Iksha.