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
Space Redistribution ProcessOriginal: " hello world "Spaces: 7Words: [hello, world]Gaps: 1Calculate7 รท 1 = 7remainder: 0Distribute7 spaces between0 spaces at endResult: "hello world"Perfect distribution achieved!
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
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
18.5K Views
Medium Frequency
~8 min Avg. Time
842 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