Skip to contentKEEP THE CRAFTTHE SANCTUARY

Find K Closest Elements

Binary search for where the best block of k neighbours of x starts in a sorted array.

The problem

Implement Solution.findClosestElements(arr, k, x). arr is sorted in ascending order. Return the k values of arr that are closest to x, in ascending order. Value a is closer than value b when |a - x| < |b - x|, or when the distances are equal and a < b. x may lie outside the range of arr. For example, arr = [1, 2, 3, 4, 5], k = 4, x = 3 returns [1, 2, 3, 4]: 1 and 5 are equally far from 3, so the smaller one wins. 1 <= k <= len(arr) <= 10000.

Starter code

class Solution:
    def findClosestElements(self, arr, k, x):
        pass

Public examples

  1. arr = [1, 2, 3, 4, 5], k = 4, x = 3gives[1, 2, 3, 4]
  2. arr = [1, 3], k = 1, x = 2gives[1]
  3. arr = [1, 2, 3, 4], k = 2, x = 9gives[3, 4]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.