#1592

Rearrange Spaces Between Words

Easy
StringString ManipulationGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach efficiently counts spaces and words, calculates how to distribute spaces, and constructs the result in a single pass. This method minimizes unnecessary iterations and string manipulations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the total number of spaces and split the text into words.
  2. 2Step 2: Calculate the number of spaces to place between each word and the extra spaces to be added at the end.
  3. 3Step 3: Use the calculated values to construct the final string in one go.
solution.py9 lines
1# Full working Python code
2
3def rearrange_spaces(text):
4    words = text.split()
5    total_spaces = text.count(' ')
6    num_words = len(words)
7    spaces_between = total_spaces // (num_words - 1) if num_words > 1 else 0
8    extra_spaces = total_spaces % (num_words - 1) if num_words > 1 else total_spaces
9    return (' ' * spaces_between).join(words) + ' ' * extra_spaces

Complexity note: The complexity is O(n) because we only traverse the string a couple of times (once to count spaces and once to join words) without any nested iterations.

  • 1Count total spaces and words efficiently.
  • 2Understand how to distribute spaces evenly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.