PracticeArrays

Clean Repeated Log Tokens

EasyArraystraversalaccumulationstate tracking Time not estimated Not started

Context

A monitoring service stores each event label as a token in the order it appeared. Bursts can repeat the same label many times in a row, making a log excerpt noisy. Create a cleaned token sequence that keeps one label for each consecutive burst while retaining separate appearances when another label occurs between them.

Problem

Implement a function that receives an ordered list of log tokens and returns a new list with each maximal run of adjacent equal tokens reduced to one representative. Preserve the order of the retained tokens. Equal tokens separated by a different token must both remain in the result. The input may be empty, and the returned list must also be empty when no tokens are supplied.

Examples

Example 1
Input: tokens = []
Output: []
Explanation: The empty input returns an empty list, as required.
Example 2
Input: tokens = ["error"]
Output: ["error"]
Explanation: The single token remains unchanged in the returned list.
Example 3
Input: tokens = ["info", "info", "warn", "info", "info", "info", "debug"]
Output: ["info", "warn", "info", "debug"]
Explanation: The two adjacent info runs are each reduced to one token, while the separated info token remains, producing ["info", "warn", "info", "debug"].

Constraints

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

Function signature

def compress_log_runs(tokens: list[str]) -> list[str]
tokens list[str]
The log tokens in their recorded order.
returns list[str]
A new token list containing exactly one representative from every maximal run of adjacent equal input tokens, in original order.

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

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