Approach 3
sort the array.
- since X - arr[i] will be monotonic. we can apply Binary Search here.
we will look for k+1 closet element.
Predicate : X - arr[i] <= arr[i+(k+1)] - X
Predicate will reduce our problem to F* T* pattern and we are interested in finding the position (index) offirst True(T).
Complexity
TC is O(nlogn) due to sorting
SC isO(1).
Pseudocode
lo = 0, hi = n-k-1;
while(lo<hi){
mid = lo+(hi-lo)/2;
if(x-arr[mid] <= arr[mid+k+1]-x){
hi = mid;
} else {
lo = mid+1;
}
}
for(int i = lo ; i<lo+k+1 ;i++){
if(arr[i]!=x) {
cout<<arr[i]<<" ";
}
}

Join Us

Hello Harsh Priyadarshi, I was trying this problem(handle: code__raider), but it is giving WA at 2nd test case only. Way 1: If I store the array, failing at 2nd test because "6 12, 7 3 5 8 1" here no. of elements should be 6 instead on 5. Please check this once.
Way2: If I don't store the array and just go with the HashMap, it is getting failed at 11th test. Approach seems alright. Please check this as well
No. of elements was a typo. It is fixed. Testcase 11 is fixed as well.
thanks Harsh, it's accepted now!!!