Rearrange Spaces Between Words - Problem
You're working with a messy text string that contains words separated by various numbers of spaces. Your task is to redistribute the spaces evenly between all words to create a clean, uniformly formatted string.
The Challenge: Given a string with words and spaces, rearrange the spaces so that there's an equal number of spaces between every pair of adjacent words, and this number should be maximized. If you can't distribute all spaces equally, place any leftover spaces at the end.
Example: " this is a sentence " becomes "this is a sentence"
Goal: Return a string of the same length where spaces are optimally redistributed between words.
Input & Output
example_1.py โ Basic Case
$
Input:
text = " this is a sentence "
โบ
Output:
"this is a sentence"
๐ก Note:
There are 9 total spaces and 3 gaps between 4 words. 9 รท 3 = 3 spaces per gap with 0 remainder, so each gap gets exactly 3 spaces.
example_2.py โ Remainder Spaces
$
Input:
text = " practice makes perfect"
โบ
Output:
"practice makes perfect "
๐ก Note:
There are 7 spaces and 2 gaps. 7 รท 2 = 3 spaces per gap with 1 remainder. Each gap gets 3 spaces, and the 1 extra space goes at the end.
example_3.py โ Single Word
$
Input:
text = " hello "
โบ
Output:
"hello "
๐ก Note:
With only one word, there are no gaps between words, so all 4 spaces are placed at the end after the single word.
Constraints
- 1 โค text.length โค 100
- text consists of lowercase English letters and spaces ' '
- text contains at least one word
- Words are separated by at least one space
Visualization
Tap to expand
Understanding the Visualization
1
Inventory
Count total bookends (spaces) and identify all books (words)
2
Calculate
Determine optimal spacing: total_bookends รท (books - 1)
3
Distribute
Place books with calculated spacing, put extra bookends at the end
Key Takeaway
๐ฏ Key Insight: The problem is essentially a division problem - distribute total spaces evenly across gaps, with remainder going to the end
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code