1. Linear Scan and Sort for Each Prefix
Intuition
For each prefix length k from 1 to |s|, loop over all words in contact. If word.substr(0, k) == s.substr(0, k), add to unique set. Sort the collected words and append to results.
When to apply: Quick brute force baseline.
Algorithm
- Step 1: Loop
kfrom 1 tos.length(). - Step 2: Prefix
pref = s.substr(0, k). - Step 3: Collect all unique contacts starting with
pref. - Step 4: Sort collected list alphabetically and add to results.
- Step 5: If list is empty, append
{"0"}or empty list.
#include <iostream>#include <string>#include <vector>#include <set>#include <algorithm>using namespace std; class Solution {public: vector<vector<string>> displayContacts(int n, string contact[], string s) { vector<vector<string>> result; set<string> uniqueContacts(contact, contact + n); string pref = ""; for (char c : s) { pref += c; vector<string> matched; for (const string& word : uniqueContacts) { if (word.rfind(pref, 0) == 0) { // startsWith matched.push_back(word); } } if (matched.empty()) matched.push_back("0"); result.push_back(matched); } return result; }}; int main() { Solution sol; string contacts[] = {"geeksforgeeks", "geeksfortest", "geeikistest"}; string s = "gee"; auto res = sol.displayContacts(3, contacts, s); for (size_t i = 0; i < res.size(); i++) { cout << "Prefix '" << s.substr(0, i + 1) << "': "; for (const string& w : res[i]) cout << w << " "; cout << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(|s| * N * L log N)— Repeats filtering and sorting for each prefix of the query string. - Space complexity:
O(N * L)— Stores contacts and output suggestion lists.
Why Brute Force Doesn't Scale:
With 50,000 contacts and 20 keystrokes, linear scan performs 1,000,000 string checks.
Trie advances 1 pointer per keystroke and only explores the relevant subtree, running in less than 5ms.