Rearrange Spaces Between Words: Distributing Spaces Evenly
LeetCode 1592, Rearrange Spaces Between Words, asks you to take a string with irregularly distributed spaces and redistribute those spaces as evenly as possible between the words. Any leftover spaces that cannot be split evenly go at the end of the string.
The problem
You are given a string text containing words separated by spaces. The spacing between words may be uneven, and there may be leading or trailing spaces. Your goal is to rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words. If the spaces do not divide evenly, the extra spaces go at the end of the resulting string.
For example, " this is a sentence " has 9 spaces and 4 words. With 3 gaps between 4 words, you place 9 // 3 = 3 spaces in each gap and 9 % 3 = 0 extra spaces at the end. The result is "this is a sentence".
The brute force approach
One way to think about this problem is to manually iterate through the string character by character, collecting words and counting spaces as you go, then assembling the result. You might build an intermediate list of word positions and space positions. This works, but it overcomplicates things. Python gives you split() which handles all the word extraction in one call, so there is no need to reinvent it.
The key insight
The total number of space characters in the input string is fixed. No spaces are added or removed. You just move them around. Once you know the total space count and the number of words, simple integer division and modulo give you everything you need: how many spaces go between each pair of words, and how many leftover spaces trail at the end.
When the input has only one word, there are zero gaps. All spaces go at the end. This edge case naturally falls out of the formula if you handle the single-word case separately (since you cannot divide by zero).
Step-by-step walkthrough
Step 1: Count total spaces
Scan the input string " this is a sentence " and count every space character.
Total spaces = 9
Step 2: Extract the words
Split the string on whitespace (ignoring leading, trailing, and consecutive spaces) to get the list of words.
Words = ["this", "is", "a", "sentence"]
Step 3: Calculate gaps between words
With 4 words there are 3 gaps. Divide 9 spaces by 3 gaps using integer division.
spaces_between = 9 // 3 = 3
Step 4: Calculate extra spaces
The remainder from the division tells you how many leftover spaces to append at the end.
extra = 9 % 3 = 0
Step 5: Build the result
Join the words with 3 spaces each, then append 0 extra spaces at the end.
Result = "this is a sentence"
The code
def reorderSpaces(text: str) -> str:
spaces = text.count(" ")
words = text.split()
if len(words) == 1:
return words[0] + " " * spaces
gap, extra = divmod(spaces, len(words) - 1)
return (" " * gap).join(words) + " " * extra
The function starts by counting every space in the input with text.count(" "). Then it extracts the words using text.split(), which automatically ignores leading, trailing, and consecutive spaces.
If there is only one word, you return that word followed by all the spaces. Otherwise, divmod gives you the number of spaces per gap and the leftover count in one call. You join the words with the per-gap spaces and tack the extras onto the end.
Python's divmod(a, b) returns (a // b, a % b) in a single operation. It is a clean way to get both the quotient and remainder when you need them together.
Complexity analysis
| Approach | Time | Space |
|---|---|---|
| Count and redistribute | O(n) | O(n) |
Time: You scan the string once to count spaces, once to split into words, and once to join them back. Each pass is O(n), so the total is O(n).
Space: The list of words and the final result string each take O(n) space. You cannot avoid this since you need to produce a new string as output.
The building blocks
Space counting and distribution
Counting occurrences of a character in a string and distributing a total evenly across slots is a pattern that appears in many problems. Any time you need to "spread" a quantity across bins, integer division gives you the per-bin amount and modulo gives you the remainder. You will see this same idea in problems about distributing candies, balancing loads, or formatting text.
Word extraction with split
Python's split() (with no arguments) handles all whitespace variations: leading spaces, trailing spaces, multiple consecutive spaces. It returns just the words. This is a common building block for string parsing problems. Understanding what split() does under the hood (skip spaces, collect non-spaces, repeat) helps you reason about string problems even when you need to implement the logic manually.
Edge cases
Single word. If the text contains only one word (like " hello "), there are no gaps to fill. All spaces go at the end, producing "hello ".
No extra spaces. When the spaces divide evenly among the gaps (like 9 spaces across 3 gaps), the remainder is 0 and nothing is appended at the end.
Spaces only at one end. Input like "hello " has one word and 3 spaces. The result is "hello ", unchanged.
Two words. With only one gap, all spaces go between the two words. For " a b " (3 spaces, 2 words), the result is "a b".
From understanding to recall
You might read through this solution and think it is obvious. Count spaces, divide by gaps, join. But the next time you see a string formatting problem in an interview, will the divmod trick and the edge case for a single word come to mind immediately?
That is where spaced repetition helps. By revisiting this problem at increasing intervals, you reinforce not just the solution but the pattern: count a resource, distribute it evenly, handle the remainder. After a few review sessions spread over days, the approach becomes automatic.
The building blocks here (character counting, split() behavior, divmod for even distribution) are reusable across dozens of problems. Drilling them in isolation ensures they are ready when you need them, not buried under a pile of half-remembered solutions.
Related posts
- Reverse Words in a String - String word manipulation with space handling
- Length of Last Word - Parsing words from strings with trailing spaces
- Rearrange Words in a Sentence - Reordering words within a string