1. Brute Force — Full Sort
Intuition
Sort the entire array in descending order. Return the element at index k-1.
When to apply: When simplicity is paramount and N is small.
Algorithm
- Step 1: Sort nums descending.
- Step 2: Return nums[k - 1].
#include <iostream>#include <vector>#include <algorithm>using namespace std; class Solution {public: int findKthLargest(vector<int>& nums, int k) { sort(nums.rbegin(), nums.rend()); return nums[k - 1]; }}; int main() { Solution sol; vector<int> nums = {3, 2, 1, 5, 6, 4}; cout << "Kth Largest (Brute Force): " << sol.findKthLargest(nums, 2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— O(N log N) comparison sort. - Space complexity:
O(1) auxiliary— O(1) in-place auxiliary space.
Why Brute Force Doesn't Scale:
With N = 105, O(N log N) requires ~1.7 * 106 comparisons. Quickselect completes in ~2 * 105 comparisons.
Quickselect executes in ~3ms vs ~25ms for sorting.