File: reverse-words-in-a-string-iii/solution.py

Date: 2026-06-06

Time: 18:55

Purpose

This file implements the solution for LeetCode 557 — Reverse Words in a String III. It owns a single responsibility: given a sentence, reverse the characters within each word while keeping word order and spacing intact.

Key Components

reversewordsin_string(s: str) -> str

The sole public function. Contract:

Patterns

One-liner generator expression. The entire solution chains three operations into a single return statement:

1. s.split(" ") — tokenize on literal space (not whitespace generally)

2. word[::-1] — reverse each token via Python's slice-step idiom

3. " ".join(...) — reassemble with single-space delimiter

This is a common pattern across the repo's easy-level solutions: a composable pipeline of built-in string/list operations, no intermediate variables.

Explicit space delimiter. split(" ") rather than split() is deliberate — split() without arguments would collapse multiple spaces and strip leading/trailing whitespace. Using " " preserves the structural assumption that the input has exactly single-space separators, which matches the LeetCode problem guarantee.

Dependencies

Imports: None — pure stdlib, no external or internal imports.

Imported by: The "Imported By" list in the prompt is misleading — those ~400+ test files don't actually import *this* solution. They appear to be an artifact of the repo's test harness structure where each testsolution.py imports its sibling solution.py via a shared pattern. The real consumer is reverse-words-in-a-string-iii/testsolution.py.

Flow


"Let's take LeetCode"
    → split(" ") → ["Let's", "take", "LeetCode"]
    → [::-1] each → ["s'teL", "ekat", "edoCteeL"]
    → join(" ")  → "s'teL ekat edoCteeL"

Single pass over the string (split) + one pass per word (reverse) + one pass to join. Effectively O(n) where n is total character count.

Invariants

Error Handling

None. The function trusts its input matches the LeetCode contract. No validation, no try/except. Passing None would raise AttributeError; passing non-string types would fail at .split().

Topics to Explore

Beliefs