PracticeArrays

Group Consecutive Document Tokens

EasyArraystraversalstate trackingaccumulation Time not estimated Not started

Context

A document-quality tool receives a stream of normalized words from a text file. Repeated neighboring words can indicate emphasis or accidental duplication, so the tool records each uninterrupted stretch as one group while preserving the document’s order.

Problem

Write a function that partitions a list of document tokens into maximal contiguous groups. A group contains consecutive tokens that are all identical. Start a new group whenever the next token differs from the token in the active group. Equal tokens separated by another token must belong to different groups. Return the groups in their original order. If the input list is empty, return an empty list. Each token appears in exactly one returned group.

Examples

Example 1
Input: tokens = ["read", "read", "carefully", "carefully", "read"]
Output: [["read", "read"], ["carefully", "carefully"], ["read"]]
Explanation: The executed result groups the adjacent "read" tokens, then the adjacent "carefully" tokens, and keeps the final separated "read" in its own group: [["read", "read"], ["carefully", "carefully"], ["read"]].
Example 2
Input: tokens = ["alpha", "beta", "gamma"]
Output: [["alpha"], ["beta"], ["gamma"]]
Explanation: The executed result places each token in its own group because each adjacent pair differs: [["alpha"], ["beta"], ["gamma"]].
Example 3
Input: tokens = []
Output: []
Explanation: The executed result is an empty list for the empty input.

Constraints

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

Function signature

def group_document_runs(tokens: list[str]) -> list[list[str]]
tokens list[str]
The document tokens in reading order.
returns list[list[str]]
A list of groups, where each inner list is one maximal uninterrupted run of identical neighboring tokens.

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

Approved · cc018-abs_178_v214 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1