Rearrange Spaces Between Words - Problem
You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.
Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.
Return the string after rearranging the spaces.
Input & Output
Example 1 — Multiple Words with Extra Spaces
$
Input:
text = " this is a sentence "
›
Output:
"this is a sentence"
💡 Note:
9 total spaces distributed among 3 gaps = 3 spaces per gap with 0 remainder
Example 2 — Uneven Distribution
$
Input:
text = " hello world "
›
Output:
"hello world "
💡 Note:
5 total spaces with 1 gap = 5 spaces between words, no remainder goes at end
Example 3 — Single Word
$
Input:
text = " hello "
›
Output:
"hello "
💡 Note:
Single word case: all 4 spaces go at the end after the word
Constraints
- 1 ≤ text.length ≤ 100
- text consists of lowercase English letters and spaces ' '
- text contains at least one word
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Identify words and count total spaces in the string
2
Space Distribution
Calculate spaces per gap and handle remainder
3
Output Construction
Rebuild string with evenly distributed spaces
Key Takeaway
🎯 Key Insight: Extract words, count total spaces, then redistribute evenly with remainder at the end
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code