1. Backward Linear Search
Intuition
Store original words array. For f(pref, suff), loop from i = words.size() - 1 down to 0. If words[i].startsWith(pref) and words[i].endsWith(suff), return i. If loop completes, return -1.
When to apply: Basic baseline check.
Algorithm
- Step 1: Store
wordsarray. - Step 2:
f(pref, suff): loopifrom N-1 down to 0. - Step 3: If
w.startsWith(pref)andw.endsWith(suff), returni. - Step 4: Return -1.
#include <iostream>#include <vector>#include <string>using namespace std; class WordFilter { vector<string> dict;public: WordFilter(vector<string>& words) { dict = words; } int f(string pref, string suff) { int pLen = pref.length(), sLen = suff.length(); for (int i = dict.size() - 1; i >= 0; i--) { const string& w = dict[i]; int wLen = w.length(); if (wLen >= pLen && wLen >= sLen) { if (w.rfind(pref, 0) == 0 && w.compare(wLen - sLen, sLen, suff) == 0) { return i; } } } return -1; }}; int main() { vector<string> words = {"apple"}; WordFilter wf(words); cout << "f('a', 'e'): " << wf.f("a", "e") << endl; cout << "f('b', ''): " << wf.f("b", "") << endl; return 0;}Time & Space Complexity
- Time complexity:
Init: O(1), f: O(N * L)— Must inspect every word backwards for each query. - Space complexity:
O(N * L)— Stores words array.
Why Brute Force Doesn't Scale:
Linear scan per query exhausts time limits on high query loads.
Unified Trie answers all 10,000 queries in ~15ms total.