Time:O(|\texttt{text}|) Space:O(|\texttt{text}|) C++ class Solution { public: string reorderSpaces(string text) { const int spaces = count(begin(text), end(text), ' '); string ans; vector<string> words; istringstream iss(text); string word; while (iss >> word) words.push_back(word); if (words.size() == 1) return word + string(spaces, ' '); const int gapSize = spaces / (words.size() - 1); const int remains = spaces % (words.size() - 1); for (int i = 0; i < words.size() - 1; ++i) ans += words[i] + string(gapSize, ' '); ans += words.back() + string(remains, ' '); return ans; } }; JAVA class Solution { public String reorderSpaces(String text) { final String[] words = text.trim().split("\\s+"); final int spaces = (int) text.chars().filter(c -> c == ' ').count(); final int n = words.length; final int gapSize = n == 1 ? 0 : spaces / (n - 1); final int remains = n == 1 ? spaces : spaces % (n - 1); return String.join(" ".repeat(gapSize), words) + " ".repeat(remains); } }