- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 56 lines of C++ from the credited upstream file rearrange-words-in-a-sentence.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution {5public:6 string arrangeWords(string text) {7 text.front() = tolower(text.front());8 stringstream ss(text);9 string word;10 map<int, string> lookup;11 while (ss >> word) {12 lookup[word.size()] += word + " ";13 }14 string result;15 for (const auto& [_, word]: lookup) {16 result += word;17 }18 result.pop_back();19 result.front() = toupper(result.front());20 return result;21 }22};23 242526class Solution2 {27public:28 string arrangeWords(string text) {29 text.front() = tolower(text.front());30 auto words = split(text, ' ');31 stable_sort(begin(words), end(words),32 [](const string &s1, const string &s2) {33 return s1.size() < s2.size();34 });35 string result;36 for (const auto& word : words) {37 result += word + " ";38 }39 result.pop_back();40 result.front() = toupper(result.front());41 return result;42 }43 44private:45 vector<string> split(const string& s, const char delim) {46 vector<string> result;47 auto end = string::npos;48 do {49 const auto& start = end + 1;50 end = s.find(delim, start);51 result.emplace_back(s.substr(start, end - start));52 } while (end != string::npos); 53 return result;54 }55};56