1. List Storage with Character-by-Character Comparison
Intuition
Store words in vector<string>. On search(pattern), filter words of matching length and check if every char matches or is '.'. Return true on first match.
When to apply: Quick prototype when number of searches is tiny.
Algorithm
- Step 1:
addWord(word): appendwordtowordsList. - Step 2:
search(word): loop through eachwinwordsList. - Step 3: If
w.length() != word.length(), continue. - Step 4: Check if
word[k] == '.' || word[k] == w[k]for all characters. - Step 5: If all match, return true. If loop completes, return false.
#include <iostream>#include <string>#include <vector>using namespace std; class WordDictionary { vector<string> words;public: WordDictionary() {} void addWord(string word) { words.push_back(word); } bool search(string word) { int len = word.length(); for (const string& w : words) { if (w.length() != len) continue; bool match = true; for (int i = 0; i < len; i++) { if (word[i] != '.' && word[i] != w[i]) { match = false; break; } } if (match) return true; } return false; }}; int main() { WordDictionary dict; dict.addWord("bad"); dict.addWord("dad"); dict.addWord("mad"); cout << "search(\"pad\"): " << (dict.search("pad") ? "true" : "false") << endl; cout << "search(\"bad\"): " << (dict.search("bad") ? "true" : "false") << endl; cout << "search(".ad"): " << (dict.search(".ad") ? "true" : "false") << endl; return 0;}Time & Space Complexity
- Time complexity:
addWord: O(1), search: O(N * L)— Must iterate up to N words and perform L character comparisons each. - Space complexity:
O(N * L)— Stores all N words of length L.
Why Brute Force Doesn't Scale:
With 10,000 words and 10,000 search calls, brute force performs 108 string operations, timing out.
Trie reduces non-wildcard queries to O(L) <= 25 steps, answering queries in microseconds.