1. Split, Filter, Reverse, and Join
Intuition
Use built-in string splitting functions on whitespace. Discard empty tokens resulting from consecutive spaces. Reverse the array of words and join them with a single space delimiter.
When to apply: Basic high-level language built-in solution.
Algorithm
- Split
sinto tokens. - Filter out empty tokens.
- Reverse array of tokens.
- Join tokens with
' '. - Return result.
Split, Filter, Reverse, and Join
2 of 2 questions left todayObservation: Input string contains 4 words separated by spaces
Observation: Input string contains 4 words separated by spaces.
Decision: Split string using whitespace delimiter into token list: ['the', 'sky', 'is', 'blue'].
Invariant: Splitting extracts intact words regardless of internal space counts.
#include <iostream>#include <string>#include <vector>#include <sstream>#include <algorithm> class Solution {public: std::string reverseWords(std::string s) { std::stringstream ss(s); std::string word; std::vector<std::string> words; while (ss >> word) { words.push_back(word); } std::reverse(words.begin(), words.end()); std::string res = ""; for (int i = 0; i < (int)words.size(); ++i) { if (i > 0) res += " "; res += words[i]; } return res; }}; int main() { Solution sol; std::cout << sol.reverseWords("the sky is blue") << std::endl; // "blue is sky the" std::cout << sol.reverseWords(" hello world ") << std::endl; // "world hello" return 0;}Time & Space Complexity
- Time complexity:
O(N)— Splits and joins N characters across memory buffers. - Space complexity:
O(N)
Why Brute Force Doesn't Scale:
Two-pointer in-place whitespace compaction avoids extra string allocations.
Strict O(1) auxiliary space in mutable string environments like C++.