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
Rearrange Spaces Between WordsInput:" this is a sentence "Analysis:"this""is""a""sentence"Words: 4 | Total Spaces: 9 | Gaps: 3Distribution: 9 ÷ 3 = 3 spaces per gap, 0 remainderOutput:"this is a sentence"Equal spacing: 3 spaces between each adjacent word pair
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
Asked in
Facebook 15 Microsoft 12
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen