Back to blog
Jan 15, 2025
3 min read

Rearrange Spaces Between Words

Rearrange spaces between words to distribute them equally, placing extra spaces at the end.

Difficulty: Easy | Acceptance: 44.20% | Paid: No Topics: String

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 distribute all 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.

Examples

Example 1

Input:

text = "  this   is  a sentence "

Output:

"this   is   a   sentence"

Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.

Example 2

Input:

text = " practice   makes   perfect"

Output:

"practice   makes   perfect "

Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.

Constraints

1 <= text.length <= 100
text consists of lowercase English letters and spaces ' '.
text contains at least one word.

Count and Distribute

Intuition Count total spaces and extract words using built-in split, then calculate equal distribution between words with remainder at the end.

Steps

  • Count total spaces in the string
  • Extract all words using split
  • Handle single word edge case (all spaces at end)
  • Calculate spaces between words and extra spaces
  • Join words with calculated gaps and append extra spaces
python
class Solution:
    def reorderSpaces(self, text: str) -&gt; str:
        total_spaces = text.count(' ')
        words = text.split()
        num_words = len(words)
        
        if num_words == 1:
            return words[0] + ' ' * total_spaces
        
        spaces_between = total_spaces // (num_words - 1)
        extra_spaces = total_spaces % (num_words - 1)
        
        result = (' ' * spaces_between).join(words)
        result += ' ' * extra_spaces
        
        return result

Complexity

  • Time: O(n) where n is the length of text
  • Space: O(n) for storing words and result
  • Notes: Clean and readable using built-in string methods

Iterative Parsing

Intuition Manually parse the string character by character to count spaces and collect words, then build the result with calculated spacing.

Steps

  • Iterate through each character counting spaces and building words
  • Store completed words in a list
  • Calculate spaces between words and remainder
  • Build result by appending words with gaps between them
python
class Solution:
    def reorderSpaces(self, text: str) -&gt; str:
        total_spaces = 0
        words = []
        current_word = []
        
        for c in text:
            if c == ' ':
                total_spaces += 1
                if current_word:
                    words.append(''.join(current_word))
                    current_word = []
            else:
                current_word.append(c)
        
        if current_word:
            words.append(''.join(current_word))
        
        num_words = len(words)
        
        if num_words == 1:
            return words[0] + ' ' * total_spaces
        
        spaces_between = total_spaces // (num_words - 1)
        extra_spaces = total_spaces % (num_words - 1)
        
        result = []
        for i, word in enumerate(words):
            result.append(word)
            if i &lt; num_words - 1:
                result.append(' ' * spaces_between)
        
        result.append(' ' * extra_spaces)
        
        return ''.join(result)

Complexity

  • Time: O(n) where n is the length of text
  • Space: O(n) for storing words and result
  • Notes: More explicit parsing logic, useful when built-in split is unavailable