1. Brute Force — Sort by Custom Distance Comparator
Intuition
Clone array, sort using comparator (abs(a - x), a), slice first k elements, and sort the result in ascending order.
When to apply: When simplicity is valued over time efficiency and N is small.
Algorithm
- Step 1: Create a copy of the array.
- Step 2: Sort by custom comparator: abs(a - x) < abs(b - x) or (abs(a - x) == abs(b - x) && a < b).
- Step 3: Take the first k elements.
- Step 4: Sort these k elements in ascending order and return.
#include <iostream>#include <vector>#include <cmath>#include <algorithm>using namespace std; class Solution {public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { vector<int> sortedArr = arr; sort(sortedArr.begin(), sortedArr.end(), [x](int a, int b) { int d1 = abs(a - x); int d2 = abs(b - x); if (d1 != d2) return d1 < d2; return a < b; }); vector<int> result(sortedArr.begin(), sortedArr.begin() + k); sort(result.begin(), result.end()); return result; }}; int main() { Solution sol; vector<int> arr = {1, 2, 3, 4, 5}; vector<int> res = sol.findClosestElements(arr, 4, 3); cout << "K Closest (Brute Force): "; for (int v : res) cout << v << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— O(N log N) dominated by full array sorting. - Space complexity:
O(N)— O(N) auxiliary space to clone and sort the array.
Why Brute Force Doesn't Scale:
With N = 105, O(N log N) takes ~1.7 * 106 ops. Binary search takes O(log N) which is only ~17 operations.
Binary search takes ~0.01ms versus ~30ms for sorting.