# 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.

{% tabs %}
{% tab title="Scala" %}

```scala
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)
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.bernardw.com/problems/find-k-closest-elements-to-a-given-value.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
