educative.io

Educative

K closest Number - Alternative Solution (Simpler) using previous question

Hi I made this solution using previous questions. This does not use Binary Search, and seems much simpler. Is there a reason why this wouldn’t work or the Binary Search solution would be better? please help

const Heap = require('./collections/heap'); //http://www.collectionsjs.com

const find_closest_elements = function(arr, K, X) {
  result = new Heap([], null, (a,b) => Math.abs(a - X) - Math.abs(b - X));

  for (i = 0; i < arr.length; i++) {
if (result.length < K) {
  result.push(arr[i])
} else {
  if (Math.abs(arr[i] - X) < Math.abs(result.peek() - X)) {
    result.pop()
    result.push(arr[i])
  }
}
  }

  return result.toArray();
};

because it’s a O(nlogK) solution. with an sorted input, we can do it better using binary search