LeetCode Problem Workspace

Rearrange Spaces Between Words

Rearrange spaces between words by distributing them evenly, placing any leftover spaces at the end to match original text length.

category

1

Topics

code_blocks

6

Code langs

hub

3

Related

Practice Focus

Easy · String-driven solution strategy

bolt

Answer-first summary

Rearrange spaces between words by distributing them evenly, placing any leftover spaces at the end to match original text length.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for String-driven solution strategy

Try AiBox Copilotarrow_forward

Start by counting the total spaces and identifying all words in the input text. Calculate how many spaces can be evenly placed between words using integer division, and append any leftover spaces at the end. This approach ensures the returned string preserves the original length while maximizing spacing consistency between words.

Problem Statement

Given a string text containing words separated by spaces, rearrange the spaces such that every pair of adjacent words has the same number of spaces between them, maximizing this number. If any spaces remain after equal distribution, append them at the end to maintain the string's original length.

Each word consists of lowercase English letters and is guaranteed to be separated by at least one space. Return the final string after redistributing spaces so that it preserves the total number of characters and evenly spaces words according to the rules above.

Examples

Example 1

Input: text = " this is a sentence "

Output: "this is a sentence"

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 "

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 ' '.
  • text contains at least one word.

Solution Approach

Count Words and Spaces

Scan the string to count the total number of spaces and extract all words. These counts are critical for determining how many spaces go between each word.

Compute Space Distribution

Use integer division to calculate spaces between words: total_spaces divided by (number_of_words - 1). The remainder represents leftover spaces, which will be appended at the end.

Construct the Result

Join the words with the calculated number of spaces between each, then append any leftover spaces at the end. This ensures the output string length matches the original text while following the maximal even spacing rule.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Time complexity is O(n) to scan the string and count words and spaces. Space complexity is O(n) for storing words and building the output string.

What Interviewers Usually Probe

  • Looking for efficient string parsing without extra passes over the text.
  • Expect candidate to handle cases with a single word where no spaces can be distributed between words.
  • Watch for correct placement of leftover spaces at the end to preserve original string length.

Common Pitfalls or Variants

Common pitfalls

  • Forgetting to handle the single-word edge case, which requires all spaces at the end.
  • Incorrectly dividing spaces when words are fewer than two, leading to division by zero.
  • Appending leftover spaces incorrectly, breaking the original string length constraint.

Follow-up variants

  • Redistribute spaces but preserve punctuation attached to words.
  • Maximize spacing while also aligning words to the right side of the string.
  • Redistribute spaces evenly for multi-line strings where each line must maintain its original length.

FAQ

How do I handle a string with only one word in "Rearrange Spaces Between Words"?

All spaces should be appended at the end since no spaces can exist between words, ensuring the string length remains the same.

What is the main pattern for solving this problem efficiently?

Use a string-driven solution strategy: count words and spaces, then divide spaces evenly between words.

How do I deal with leftover spaces after equal distribution?

Append any leftover spaces to the end of the string so that the output matches the original length.

Can this approach handle leading and trailing spaces?

Yes, the algorithm counts all spaces regardless of position and redistributes them according to the problem rules.

Why is integer division used in this problem?

Integer division determines the maximum number of spaces that can be evenly placed between words while separating leftover spaces for the end.

terminal

Solution

Solution 1: String Simulation

First, we count the number of spaces in the string $\textit{text}$, denoted as $\textit{spaces}$. Then, we split $\textit{text}$ by spaces into an array of strings $\textit{words}$. Next, we calculate the number of spaces that need to be inserted between adjacent words and perform the concatenation. Finally, we append the remaining spaces to the end.

1
2
3
4
5
6
7
8
class Solution:
    def reorderSpaces(self, text: str) -> str:
        spaces = text.count(" ")
        words = text.split()
        if len(words) == 1:
            return words[0] + " " * spaces
        cnt, mod = divmod(spaces, len(words) - 1)
        return (" " * cnt).join(words) + " " * mod
Rearrange Spaces Between Words Solution: String-driven solution strategy | LeetCode #1592 Easy