diff --git a/cpp/0658-find-k-closest-elements.cpp b/cpp/0658-find-k-closest-elements.cpp new file mode 100644 index 000000000..291a90694 --- /dev/null +++ b/cpp/0658-find-k-closest-elements.cpp @@ -0,0 +1,61 @@ +// Approach: Binary Search + Two‑Pointer Window Expansion (More Intuitive) +// Runtime: 0 ms (100%); Memory: 35.7 MB (99%) +// Time Complexity: O(log(n) + k), Space Complexity: O(1) + +class Solution { +public: + vector findClosestElements(vector& arr, int k, int x) { + + // Part 1: Binary Sarch to find x or element in arr closest to x + int l=0; + int r = arr.size()-1; + int closestVal = arr[0]; + int closestIndex = 0; + + while(l<=r){ + int m = (l+r)/2; + int currDiff = abs(arr[m] - x); + int resDiff = abs(closestVal - x); + + if((currDiff< resDiff) || (currDiff == resDiff && arr[m]x){ + r= m-1; + } + else{ + break; + } + + } + + //Part 2: Binary Search to find the window of k such elements + l=closestIndex; + r=closestIndex; + + for( int i=0; i(arr.begin() + l, arr.begin() + r + 1); + + } +}; \ No newline at end of file