File: sorting-the-sentence/solution.py

Date: 2026-06-06

Time: 19:13

sorting-the-sentence/solution.py

Purpose

This file solves LeetCode 1859 — Sorting the Sentence. It takes a "shuffled sentence" — where each word has its original 1-indexed position appended as a trailing digit — and reconstructs the original sentence by placing each word at its correct position.

For example: "is2 sentence4 This1 a3""This is a sentence".

Key Components

Solution.sort_sentence(self, s: str) -> str — The single public method. Contract:

Flow

1. Split the input on whitespace into tokens (e.g., ["is2", "sentence4", "This1", "a3"]).

2. Allocate a result array sized to the number of tokens.

3. Place each token: extract the last character as the 1-indexed position, strip it off, and write the word into result[pos - 1].

4. Join and return the result array with spaces.

The approach is a single-pass scatter: iterate the shuffled words once and directly place each one. This avoids sorting entirely — it's O(n) in both time and space (where n is the number of words).

Patterns

Dependencies

Invariants

Error Handling

None. The code trusts the caller to provide valid input per the LeetCode contract. Invalid trailing characters, out-of-range positions, or duplicate positions produce silent wrong answers or exceptions — appropriate for a competitive programming context where inputs are guaranteed well-formed.

Topics to Explore

Beliefs