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
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
💡
Explanation
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code
Test Cases
0 passed
0 failed
3 pending