1. Brute Force — Full Sort on Unique Words
Intuition
Count frequencies of each word. Extract unique words into a list and sort with comparator: if count != count return count > count; else return word < word.
When to apply: When total words count is small (N <= 1000).
Algorithm
- Step 1: Count frequency of each word in hash map.
- Step 2: Collect unique words into a list.
- Step 3: Sort list using custom comparator: freq descending, word ascending.
- Step 4: Return first k words.
#include <iostream>#include <vector>#include <string>#include <unordered_map>#include <algorithm>using namespace std; class Solution {public: vector<string> topKFrequent(vector<string>& words, int k) { unordered_map<string, int> freq; for (const string& w : words) freq[w]++; vector<string> unique; for (auto& [w, count] : freq) unique.push_back(w); sort(unique.begin(), unique.end(), [&](const string& a, const string& b) { if (freq[a] != freq[b]) return freq[a] > freq[b]; return a < b; }); return vector<string>(unique.begin(), unique.begin() + k); }}; int main() { Solution sol; vector<string> words = {"i","love","leetcode","i","love","coding"}; auto res = sol.topKFrequent(words, 2); cout << "Top K Words (Brute Force): "; for (const string& w : res) cout << w << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N + U log U)— O(N + U log U) sorting unique words. - Space complexity:
O(U)— O(U) storage for hash map and list.
Why Brute Force Doesn't Scale:
When U = 100,000 and K = 10, full sorting takes 100,000 * 17 ops, while Min-Heap takes 100,000 * 3.3 ops (5x faster) and uses O(K) heap memory.
Min-Heap runs in ~5ms for K = 10.