1. Brute Force — Flatten Matrix & Sort
Intuition
Copy all N2 elements into a 1D vector. Sort the vector ascending and return the element at index k-1.
When to apply: When simplicity is preferred and matrix size is small (n <= 50).
Algorithm
- Step 1: Flatten matrix into a 1D array.
- Step 2: Sort the array ascending.
- Step 3: Return array[k - 1].
#include <iostream>#include <vector>#include <algorithm>using namespace std; class Solution {public: int kthSmallest(vector<vector<int>>& matrix, int k) { vector<int> flat; for (auto& row : matrix) { for (int val : row) flat.push_back(val); } sort(flat.begin(), flat.end()); return flat[k - 1]; }}; int main() { Solution sol; vector<vector<int>> matrix = {{1,5,9},{10,11,13},{12,13,15}}; cout << "Kth Smallest (Brute Force): " << sol.kthSmallest(matrix, 8) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2 log(N^2))— O(N2 log N) comparison sort. - Space complexity:
O(N^2)— O(N2) storage.
Why Brute Force Doesn't Scale:
For n = 300, N2 = 90,000. Heap takes O(K log N) which is ~90,000 * 9 ops. Binary search takes 300 * 32 = ~9,600 ops (100x faster) and uses 0 extra memory.
Binary search runs in ~0.5ms with 0 memory allocations.