File: rearrange-spaces-between-words/solution.py

Date: 2026-06-06

Time: 18:40

rearrange-spaces-between-words/solution.py

Purpose

This file solves LeetCode 1592: Rearrange Spaces Between Words. Given a string with words separated by (possibly irregular) spaces, redistribute all spaces evenly between words, with any remainder appended to the end.

Key Components

reorderSpaces(text: str) -> str — The sole function. Contract:

Flow

1. Count total spacestext.count(' ') counts every space in the original string, regardless of position.

2. Extract wordstext.split() splits on any whitespace and discards empties, so " hello world " yields ["hello", "world"].

3. Single-word edge case — If only one word exists, there are zero gaps between words. All spaces go after the word: words[0] + ' ' * total_spaces.

4. Even distributiondivmod(total_spaces, len(words) - 1) computes between (spaces per gap) and extra (leftover spaces for the end).

5. Reassemble — Join words with between spaces, append extra spaces.

Patterns

Dependencies

Invariants

Error Handling

None. The function assumes valid input per the LeetCode contract (non-empty string with at least one word). No explicit validation, no exceptions raised. An empty string would cause words[0] to raise IndexError — but that's outside the problem's input constraints.

Beliefs