PracticeSimulation

Flip Neighboring Log Tokens

EasySimulationtraversalstate trackingindex arithmetic Time not estimated Not started

Context

Mira is cleaning short event logs before displaying them. Each log is stored as an ordered list of tokens. To create a mirrored rhythm, she wants every neighboring pair exchanged: the first and second tokens trade places, then the third and fourth, and so on. If the log has an odd number of tokens, its final token has no partner and stays at the end.

Problem

Write a function that transforms the supplied token list by reversing each consecutive non-overlapping pair from left to right. Process positions 0 and 1 as one pair, positions 2 and 3 as the next, and continue in the same way. Include every token exactly once in the returned list, including repeated tokens. When the input length is odd, preserve the final unpaired token at the end. An empty list must produce an empty list, and a one-token list must preserve that token.

Examples

Example 1
Input: tokens = ["login", "user", "success", "audit"]
Output: ["user", "login", "audit", "success"]
Explanation: The executed output is ["user", "login", "audit", "success"], reversing the pairs ["login", "user"] and ["success", "audit"].
Example 2
Input: tokens = ["open", "file", "read"]
Output: ["file", "open", "read"]
Explanation: The executed output is ["file", "open", "read"], reversing ["open", "file"] and preserving the final unpaired token.
Example 3
Input: tokens = ["retry", "retry", "close", "error", "retry"]
Output: ["retry", "retry", "error", "close", "retry"]
Explanation: The executed output is ["retry", "retry", "error", "close", "retry"], reversing each complete pair while preserving the final "retry" token.

Constraints

  • 0 <= len(tokens) <= 100000
  • 1 <= len(tokens[i]) <= 40 for every i
  • Types: tokens is str[]; result is str[]

Function signature

def flip_log_tokens(tokens: list[str]) -> list[str]
tokens list[str]
The ordered tokens from one event log.
returns list[str]
A new token list in which each complete adjacent pair from the input appears in reversed order, with any final unpaired token unchanged at the end.

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

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