PracticeArrays

Flip the Token Order in Every Document

EasyArraystraversalstate trackingcomparison Time not estimated Not started

Context

A text archive stores each document as a separate list of compact token labels. A cleanup stage needs to read every document from its final token back to its first token, while keeping documents separate. Build the transformation that reverses each document independently.

Problem

Given a collection of documents, where each document is represented by a sequence of token labels, reverse the token order inside every document. Keep the outer collection unchanged: preserve the number of documents, each document's length, every token, and every document boundary. An empty archive is valid, and an empty or one-token document must remain valid and require no special placeholder. Repeated token labels must stay repeated and simply appear in the opposite positions. Return the transformed collection.

Examples

Example 1
Input: documents = [["alpha", "beta", "gamma"], ["red", "red", "blue"], ["solo"]]
Output: [["gamma", "beta", "alpha"], ["blue", "red", "red"], ["solo"]]
Explanation: The first document changes from ["alpha", "beta", "gamma"] to ["gamma", "beta", "alpha"], the repeated labels in the second document remain repeated in reversed positions, and the one-token document remains ["solo"].
Example 2
Input: documents = [[], ["open", "ai"], [], ["token"]]
Output: [[], ["ai", "open"], [], ["token"]]
Explanation: The empty documents remain empty, ["open", "ai"] becomes ["ai", "open"], and the one-token document remains ["token"].
Example 3
Input: documents = [["a1", "b2"], ["cat", "dog", "cat"], ["x9", "y8", "z7"]]
Output: [["b2", "a1"], ["cat", "dog", "cat"], ["z7", "y8", "x9"]]
Explanation: The first and third documents reverse their token orders, while ["cat", "dog", "cat"] has the same displayed order because its outer tokens are equal.

Constraints

  • 0 <= len(documents) <= 100
  • 0 <= len(documents[i]) <= 100 for every i
  • 1 <= len(documents[i][j]) <= 24 for every i, j
  • documents[i][j]: alphabet alnum lower
  • Types: documents is str[][]; result is str[][]

Function signature

def reverse_document_tokens(documents: list[list[str]]) -> list[list[str]]
documents list[list[str]]
A collection of documents, each represented by an ordered list of lowercase alphanumeric token labels.
returns list[list[str]]
The same collection shape, with the token sequence of each document reversed independently.

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

Notes

  • The outer collection and every document must remain separate.
  • The transformation is about position, not alphabetical sorting.
Approved · cb008-abs_289_v314 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1