Rearrange Spaces Between Words

Easy
265.

Rearrange Spaces Between Words

Rearrange Spaces Between Words is an easy coding problem on strings, asked in Amazon and Google interviews.

You are given a string text of words separated by spaces, with at least one word.

Rearrange the spaces so that there is an equal number between every pair of adjacent words, using as many spaces as possible. Any leftover spaces go at the end. The words themselves keep their order.

If there is only one word, all the spaces go after it.

Example 1

Input
text = " this is a sentence "
Output
this is a sentence
Explanation
Nine spaces spread evenly across three gaps.

Example 2

Input
text = " practice makes perfect"
Output
practice makes perfect
Explanation
Seven spaces give three per gap with one left over at the end.

Example 3

Input
text = "hello "
Output
hello
Explanation
One word, so every space trails it.

Constraints

  • 1 <= text.length <= 60
  • text consists of lowercase English letters and spaces.
  • text contains at least one word.
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {string} text
 * @return {string}
 */
var reorderSpaces = function(text) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Rearrange Spaces Between Words — Problem & Solution

Rearrange Spaces Between Words solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on strings.

Rearrange Spaces Between Words is an easy coding problem on strings, asked in Amazon and Google interviews.

  • Difficulty: Easy
  • Topics: Strings
  • Asked at: Amazon, Google
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

You are given a string text of words separated by spaces, with at least one word.

Rearrange the spaces so that there is an equal number between every pair of adjacent words, using as many spaces as possible. Any leftover spaces go at the end. The words themselves keep their order.

If there is only one word, all the spaces go after it.

Example 1

Input: text = "  this   is  a sentence "
Output: this   is   a   sentence
Explanation: Nine spaces spread evenly across three gaps.

Example 2

Input: text = " practice   makes   perfect"
Output: practice   makes   perfect 
Explanation: Seven spaces give three per gap with one left over at the end.

Example 3

Input: text = "hello   "
Output: hello   
Explanation: One word, so every space trails it.

Constraints

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

Hints for Rearrange Spaces Between Words

  1. Hint 1

    Count the total spaces first — that budget never changes.

  2. Hint 2

    With w words there are w - 1 gaps; each gets spaces / (w - 1) and the remainder trails the last word.

  3. Hint 3

    A single word is the special case: there are no gaps, so all the spaces trail.

How to solve Rearrange Spaces Between Words

Count the spaces once; with w words there are w - 1 gaps, each getting spaces // (w - 1), and the remainder trails the last word.

Approach

  1. Split into words and count the spaces in the original text.
  2. If there is one word, return it followed by all the spaces.
  3. Otherwise join with spaces // (w-1) spaces and append spaces % (w-1) spaces.

Why it works

The space budget is fixed; distributing it as evenly as possible across the gaps maximises the per-gap count, and whatever cannot be distributed evenly is placed at the end by the rules.

Complexity

  • Time — O(n)
  • Space — O(n)

Pitfalls

  • Dividing by w - 1 when w == 1 is a division by zero — that is why the single-word case is separate.

Reference solution

Python

def reorderSpaces(text: str) -> str:
    words = text.split()
    spaces = text.count(" ")
    if len(words) == 1:
        return words[0] + " " * spaces
    between = spaces // (len(words) - 1)
    extra = spaces - between * (len(words) - 1)
    return (" " * between).join(words) + " " * extra

Java

public static String reorderSpaces(String text) {
    List<String> words = new ArrayList<>();
    for (String w : text.split(" ")) {
        if (w.length() > 0) words.add(w);
    }
    int spaces = 0;
    for (int i = 0; i < text.length(); i++) {
        if (text.charAt(i) == ' ') spaces++;
    }
    StringBuilder out = new StringBuilder();
    if (words.size() == 1) {
        out.append(words.get(0));
        for (int i = 0; i < spaces; i++) out.append(' ');
        return out.toString();
    }
    int between = spaces / (words.size() - 1);
    int extra = spaces - between * (words.size() - 1);
    for (int i = 0; i < words.size(); i++) {
        if (i > 0) {
            for (int k = 0; k < between; k++) out.append(' ');
        }
        out.append(words.get(i));
    }
    for (int i = 0; i < extra; i++) out.append(' ');
    return out.toString();
}

C++

string reorderSpaces(string text) {
    vector<string> words;
    string cur = "";
    int spaces = 0;
    for (char c : text) {
        if (c == ' ') {
            spaces++;
            if (!cur.empty()) { words.push_back(cur); cur = ""; }
        } else {
            cur += c;
        }
    }
    if (!cur.empty()) words.push_back(cur);
    if (words.size() == 1) return words[0] + string(spaces, ' ');
    int between = spaces / ((int) words.size() - 1);
    int extra = spaces - between * ((int) words.size() - 1);
    string out = "";
    for (size_t i = 0; i < words.size(); i++) {
        if (i > 0) out += string(between, ' ');
        out += words[i];
    }
    out += string(extra, ' ');
    return out;
}

JavaScript

var reorderSpaces = function(text) {
    const words = text.split(" ").filter(function(w) { return w.length > 0; });
    let spaces = 0;
    for (let i = 0; i < text.length; i++) {
        if (text[i] === " ") spaces++;
    }
    const pad = function(n) {
        let s = "";
        for (let i = 0; i < n; i++) s += " ";
        return s;
    };
    if (words.length === 1) return words[0] + pad(spaces);
    const between = Math.floor(spaces / (words.length - 1));
    const extra = spaces - between * (words.length - 1);
    return words.join(pad(between)) + pad(extra);
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 515 strings problems · the whole catalogue

Learn the technique: Strings