Rearrange Spaces Between Words
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.
text = " this is a sentence ""this is a sentence "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;
}
Explanation
The goal is to keep the same words but spread all the spaces evenly between them, dumping any remainder at the end. The clever step is to first count the total spaces, then realize they split into equal-sized gaps using plain integer division.
We compute spaces = text.count(' ') and words = text.split() (splitting collapses runs of spaces and drops empties). If there is only one word, there are no gaps to fill, so all spaces simply trail behind it: words[0] + ' ' * spaces.
Otherwise there are len(words) - 1 gaps. Using divmod(spaces, len(words) - 1) we get gap (spaces per gap) and extra (leftover that does not divide evenly). We join the words with gap spaces each and append extra spaces at the very end.
Example: " this is a sentence " has 9 spaces and 4 words, so 3 gaps. 9 // 3 = 3 with remainder 0, giving "this is a sentence " — three spaces between each pair and the leftover (here just the final 0) trailing.