1. Scan All Roots per Word
Intuition
Split sentence into words. For each word, find all roots where word.startsWith(root). Select the shortest root. Join back into a sentence.
When to apply: Basic baseline check.
Algorithm
- Step 1: Split sentence by spaces.
- Step 2: For each word, find all roots starting the word.
- Step 3: If multiple, pick shortest root; else keep original word.
- Step 4: Join words with space and return.
#include <iostream>#include <vector>#include <string>#include <sstream>using namespace std; class Solution {public: string replaceWords(vector<string>& dictionary, string sentence) { stringstream ss(sentence); string word, result = ""; while (ss >> word) { string best = word; for (const string& root : dictionary) { if (word.rfind(root, 0) == 0) { if (root.length() < best.length()) { best = root; } } } if (!result.empty()) result += " "; result += best; } return result; }}; int main() { Solution sol; vector<string> dict = {"cat","bat","rat"}; string s = "the cattle was rattled by the battery"; cout << sol.replaceWords(dict, s) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(W * D * L)— Compares each of W words against all D roots. - Space complexity:
O(Sentence Length)— Stores split words array.
Why Brute Force Doesn't Scale:
With 1,000 words and 1,000 roots, checking takes 106 comparisons.
Trie matches each word in O(Root length) steps, completing in ~8ms.