1. Brute Force — Full Sort by Distance
Intuition
Sort the points array using a lambda comparing x12 + y12 with x22 + y22. Slice the first k elements.
When to apply: When simplicity is desired and N is small.
Algorithm
- Step 1: Sort points using comparator: (x1*x1 + y1*y1) - (x2*x2 + y2*y2).
- Step 2: Return first k elements.
#include <iostream>#include <vector>#include <algorithm>using namespace std; class Solution {public: vector<vector<int>> kClosest(vector<vector<int>>& points, int k) { sort(points.begin(), points.end(), [](const vector<int>& a, const vector<int>& b) { return (a[0]*a[0] + a[1]*a[1]) < (b[0]*b[0] + b[1]*b[1]); }); return vector<vector<int>>(points.begin(), points.begin() + k); }}; int main() { Solution sol; vector<vector<int>> points = {{3, 3}, {5, -1}, {-2, 4}}; auto res = sol.kClosest(points, 2); cout << "K Closest (Brute Force): "; for (auto& p : res) cout << "[" << p[0] << "," << p[1] << "] "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— O(N log N) from comparison sorting. - Space complexity:
O(1) auxiliary— O(1) extra memory beyond sorting.
Why Brute Force Doesn't Scale:
For N = 105, full sorting takes ~1.7 * 106 operations, while Quickselect runs in ~105 operations.
Quickselect executes in ~5ms vs ~45ms for full sorting.