PracticeArrays

Find the Greatest Document Token

EasyArraystraversalstate trackingcomparison Time not estimated Not started

Context

A text-indexing service reviews tokens extracted from a document and needs the lexicographically greatest token for a summary label. The tokens are already supplied as a list, so scan them without reordering the document data.

Problem

Implement a function that returns the lexicographically greatest token in the supplied list. Compare lowercase tokens in dictionary order, character by character. Start with a valid token as the current best, inspect every remaining token exactly once, and replace the best token whenever the current token is greater. If several tokens are equal and greatest, returning that same token is sufficient. The input is guaranteed to contain at least one token.

Examples

Example 1
Input: tokens = ["apple", "banana", "cherry", "date"]
Output: "date"
Explanation: The first example returns "date".
Example 2
Input: tokens = ["cat", "catalog", "car", "can"]
Output: "catalog"
Explanation: The second example returns "catalog".
Example 3
Input: tokens = ["zebra", "yellow", "zinc", "yak"]
Output: "zinc"
Explanation: The third example returns "zinc".

Constraints

  • 1 <= len(tokens) <= 100000
  • 1 <= len(tokens[i]) <= 30 for every i
  • tokens[i]: alphabet lowercase
  • tokens contains only lowercase letters.
  • Types: tokens is str[]; result is str

Function signature

def greatest_document_token(tokens: list[str]) -> str
tokens list[str]
A non-empty list of lowercase tokens extracted from one document.
returns str
The lexicographically greatest token in tokens.

Adapted from MBPP problem task_418 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Notes

  • The input is non-empty, so a valid first token can initialize the retained candidate.
  • Equal greatest tokens require no special tie-breaking.
Approved · cc003-abs_872_v114 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1