Skip to main content
Back to problems
#1592
Easy Algorithms

Rearrange spaces between words

String
44.1% acceptance
Feb 25, 2026
491
354
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. Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. Extra spaces go at the end. Return the string after rearranging the spaces.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn reorder_spaces(text: String) -> String {
    let spaces = text.chars().filter(|&c| c == ' ').count();
    let words: Vec<&str> = text.split_whitespace().collect();
    let nw = words.len();
    if nw == 1 {
      let mut res = words[0].to_string();
      for _ in 0..spaces {
        res.push(' ');
      }
      return res;
    }
    let gap = spaces / (nw - 1);
    let extra = spaces % (nw - 1);
    let sep: String = std::iter::repeat(' ').take(gap).collect();
    let mut res = words.join(&sep);
    for _ in 0..extra {
      res.push(' ');
    }
    res
  }
}