1. Brute Force — Sort Array on Every Add
Intuition
Store all numbers in a dynamic array. In add(val), append val, sort the entire array descending, and return index k - 1.
When to apply: When total add queries are very small (M <= 10).
Algorithm
- Step 1: In constructor, initialize array with nums.
- Step 2: In add(val), append val to array.
- Step 3: Sort array descending.
- Step 4: Return element at index k - 1.
#include <iostream>#include <vector>#include <algorithm> class KthLargest {private: int k; std::vector<int> stream; public: KthLargest(int kVal, std::vector<int>& nums) : k(kVal), stream(nums) {} int add(int val) { stream.push_back(val); std::sort(stream.begin(), stream.end(), std::greater<int>()); return stream[k - 1]; }}; int main() { std::vector<int> nums = {4, 5, 8, 2}; KthLargest kth(3, nums); std::cout << kth.add(3) << "\n"; // 4 std::cout << kth.add(5) << "\n"; // 5 std::cout << kth.add(10) << "\n"; // 5 return 0;}Time & Space Complexity
- Time complexity:
O(M * N log N)— Sorting N elements on each of M add calls takes O(M * N log N). - Space complexity:
O(N)— Stores all N elements in dynamic array.
Why Brute Force Doesn't Scale:
With 104 add operations on an array growing to 2 * 104 elements, total operations reach 104 * (2 * 104 * 14) ~ 2.8 * 109 operations, resulting in TLE.
With k = 100 and 104 additions: Min-Heap performs ~104 * log2(100) ~ 6.6 * 104 operations (< 5ms), compared to ~15 seconds for repeated sorting.