educative.io

Educative

Cleaner solution with same complexity as two pointer (O(logN+K))

Any thoughts?

def find_closest_elements(arr, K, X):
  i = max(0, bin_search(arr, X) - K)
  for j in range(i + K, len(arr)):
    if abs(X - arr[j]) < abs(X - arr[i]):
      i += 1
    else:
      break
  return arr[i: i + K]


def bin_search(arr, X):
  start = 0
  end = len(arr) - 1
  while start <= end:
    mid = start + (end - start) // 2
    if arr[mid] == X:
      return mid
    elif arr[mid] > X:
      end = mid - 1
    else:
      start = mid + 1
  return start

Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/5474975244877824

Hi @Andres_Parra ,

Most of the problems can be solved in multiple ways. Yes, your code works fine. We appreciate your efforts and thank you for sharing it.

1 Like