Find k closest elements to a given value

Given a sorted array arr[] and a value X, find the k closest elements to X in arr[].

Examples:

Input:

K = 4

X = 35

arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56}

Output:

30 39 42 45

Note that if the element is present in array, then it should not be in output, only the other closest elements are required.

def findKClosest(arr: Array[Int], target: Int, k: Int): List[Int] = {
  def findClosest(start: Int, end: Int): Int = {
    val mid = (start + end) / 2
    arr(mid) match {
      case m if m == target || (m < target && arr(mid + 1) > target) => mid
      case m if m > target => findClosest(start, mid - 1)
      case m if m < target => findClosest(mid + 1, start)
    }
  }
  if (k <= 0) Nil
  else {
    var lst: List[Int] = Nil
    val m = findClosest(0, arr.length - 1)
    var (l, r) = (m, m + 1)

    // excludes numbers equal to target
    while (l >= 0 && arr(l) == target) l -= 1
    while (r < arr.length && arr(r) == target) r += 1

    // select left/right closest
    while (lst.length < k && l >= 0 && r < arr.length) {
      if (target - arr(l) < arr(r) - target) {
        lst = arr(l) :: lst
        l -= 1
      } else {
        lst = arr(r) :: lst
        r += 1
      }
    }

    // select left/right closest if l < 0/r >= arr.length
    while (lst.length < k && r < arr.length) {
      lst = arr(r) :: lst
      r += 1
    }
    while (lst.length < k && l >= 0) {
      lst = arr(l) :: lst
      l -= 1
    }
    lst
  }
}

val arr = Array(12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56)
findKClosest(arr, 35, 4)

Last updated