Rearrange Spaces Between Words

easy string simulation

Problem

Given a string text of words separated by some number of spaces (no leading/trailing spaces guaranteed by problem? in fact may have leading/trailing spaces), rearrange so the spaces are evenly distributed between words. Any leftover spaces go at the end.

Inputtext = " this is a sentence "
Output"this is a sentence "
9 spaces total, 4 words ⇒ 3 gaps; 9 // 3 = 3 spaces between, remainder 0 trails.

def reorder_spaces(text):
    spaces = text.count(' ')
    words = text.split()
    if len(words) == 1:
        return words[0] + ' ' * spaces
    gap, extra = divmod(spaces, len(words) - 1)
    return (' ' * gap).join(words) + ' ' * extra
function reorderSpaces(text) {
  const spaces = (text.match(/ /g) || []).length;
  const words = text.trim().split(/\s+/);
  if (words.length === 1) return words[0] + ' '.repeat(spaces);
  const gap = Math.floor(spaces / (words.length - 1));
  const extra = spaces - gap * (words.length - 1);
  return words.join(' '.repeat(gap)) + ' '.repeat(extra);
}
class Solution {
    public String reorderSpaces(String text) {
        int spaces = 0;
        for (char c : text.toCharArray()) if (c == ' ') spaces++;
        String[] words = text.trim().split("\\s+");
        if (words.length == 1) {
            StringBuilder sb = new StringBuilder(words[0]);
            for (int i = 0; i < spaces; i++) sb.append(' ');
            return sb.toString();
        }
        int gap = spaces / (words.length - 1);
        int extra = spaces - gap * (words.length - 1);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            sb.append(words[i]);
            if (i < words.length - 1) for (int j = 0; j < gap; j++) sb.append(' ');
        }
        for (int j = 0; j < extra; j++) sb.append(' ');
        return sb.toString();
    }
}
string reorderSpaces(string text) {
    int spaces = 0;
    for (char c : text) if (c == ' ') spaces++;
    vector<string> words;
    string cur;
    for (char c : text) {
        if (c == ' ') { if (!cur.empty()) { words.push_back(cur); cur.clear(); } }
        else cur.push_back(c);
    }
    if (!cur.empty()) words.push_back(cur);
    if (words.size() == 1) return words[0] + string(spaces, ' ');
    int gap = spaces / (words.size() - 1);
    int extra = spaces - gap * (words.size() - 1);
    string out;
    for (size_t i = 0; i < words.size(); i++) {
        out += words[i];
        if (i + 1 < words.size()) out += string(gap, ' ');
    }
    out += string(extra, ' ');
    return out;
}
Time: O(n) Space: O(n)