1. All Pairs Prefix Comparison
Intuition
For each word w_i, test prefixes p = w_i[0..k] from length 1 up to w_i.length(). For each prefix, check if any other word w_j (j \neq i) starts with p. The first prefix that is not shared by any other word is the shortest unique prefix.
When to apply: Basic baseline check.
Algorithm
- Step 1: For each word w_i in words:
- Step 2: Loop prefix length k from 1 to w_i.length():
- Step 3: Check if any other word w_j starts with w_i.substr(0, k).
- Step 4: If no other word matches, append prefix to result and break.
- Step 5: Return result.
#include <iostream>#include <vector>#include <string>using namespace std; class Solution {public: vector<string> findPrefixes(string arr[], int n) { vector<string> result; for (int i = 0; i < n; i++) { string w = arr[i]; for (size_t k = 1; k <= w.length(); k++) { string pref = w.substr(0, k); bool unique = true; for (int j = 0; j < n; j++) { if (i != j && arr[j].rfind(pref, 0) == 0) { unique = false; break; } } if (unique) { result.push_back(pref); break; } } } return result; }}; int main() { Solution sol; string arr[] = {"zebra", "dog", "duck", "dove"}; auto res = sol.findPrefixes(arr, 4); for (const string& s : res) cout << s << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2 * L^2)— Compares all pairs across all prefix lengths. - Space complexity:
O(N * L)— Stores result array.
Why Brute Force Doesn't Scale:
With 1,000 words of length 100, brute force takes 108 string operations.
Trie with frequency counter processes all words in a single linear pass of 100,000 operations (~5ms).