1. Brute Force — Frequency Map & Sort
Intuition
Build frequency map. Extract unique keys into a list and sort by their frequency descending. Return the first k elements.
When to apply: When simplicity is desired and N is small.
Algorithm
- Step 1: Count frequency of each number in nums.
- Step 2: Extract unique elements into a list.
- Step 3: Sort list by freq[b] - freq[a].
- Step 4: Return first k elements.
#include <iostream>#include <vector>#include <unordered_map>#include <algorithm>using namespace std; class Solution {public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> freq; for (int x : nums) freq[x]++; vector<pair<int, int>> pairs; for (auto& [val, count] : freq) { pairs.push_back({count, val}); } sort(pairs.rbegin(), pairs.rend()); vector<int> result; for (int i = 0; i < k; i++) { result.push_back(pairs[i].second); } return result; }}; int main() { Solution sol; vector<int> nums = {1, 1, 1, 2, 2, 3}; auto res = sol.topKFrequent(nums, 2); cout << "Top K Frequent (Brute Force): "; for (int x : res) cout << x << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N + U log U)— O(N + U log U) sorting unique keys. - Space complexity:
O(U)— O(U) hash map storage.
Why Brute Force Doesn't Scale:
With N = 105, sorting takes ~1.7 * 106 comparisons. Bucket Sort takes exactly 105 operations.
Bucket Sort runs in ~8ms for 100,000 integers.