Rearrange Spaces Between Words

We want to redistribute the spaces in a given text string so that there is an equal number of spaces between every pair of adjacent words, and the number is maximized.

Approach

  1. Count Spaces: Determine the total number of spaces in the input string.

  2. Split Words: Separate the words from the input string into a list of words.

  3. Calculate Spaces: If there is more than one word, calculate the number of spaces to be placed between each pair of adjacent words and the number of extra spaces to be placed at the end. Otherwise, all the spaces will be placed at the end if there’s only one word.

  4. Reconstruct the String: Rebuild the string by joining the words with the calculated number of spaces between them, and adding the extra spaces at the end.

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def reorderSpaces(self, text: str) -> str:
        # Step 1: Count Spaces
        total_spaces = text.count(' ')

        # Step 2: Split Words
        words = text.split()

        # Step 3: Calculate Spaces
        if len(words) > 1:
            spaces_between_words = total_spaces // (len(words) - 1)
            extra_spaces = total_spaces % (len(words) - 1)
        else:
            spaces_between_words = 0
            extra_spaces = total_spaces

        # Step 4: Reconstruct the String
        result = (' ' * spaces_between_words).join(words) + ' ' * extra_spaces
        return result

Explanation

For text = " practice makes perfect", there are 7 spaces and 3 words. We divide the 7 spaces between the words, resulting in 3 spaces between each word, with 1 extra space at the end. The output is "practice makes perfect ".

Key Takeaways

  • The solution calculates the number of spaces and words and uses these to rearrange the spaces equally between the words.
  • The final reconstructed string maintains the same length as the original text, and it handles the case where there is only one word.
  • This approach is simple, efficient, and caters to the requirements of the problem constraints.