educative.io

Can you tell my why you used the Binary search to find X?

I solved the problem just by using the difference like Frequency Sort (medium).
This my code.
def find_closest_elements(arr, K, X):

  result = []

  min_heap=[]

  for num in arr:

      heappush(min_heap, (-abs(X-num),num))

      if len(min_heap)>K:

            heappop(min_heap)

  while len(min_heap)>0:

      _,num = heappop(min_heap)

      result.append(num)

  # TODO: Write your code here

  return result

The time complexity is O(logN).