18 · Binary Search

#658 Find K Closest Elements

Mediumsolve on LeetCode ↗

frequently reported atMetaAmazonGoogleMicrosoft

the problem

In plain words

Given a sorted array arr, an integer k and a value x, return the k values of arr that are closest to x, in ascending order. Value a is closer than b if |a − x| < |b − x|; if the distances tie, the smaller value wins.

in arr = [1,2,3,4,5], k = 4, x = 3

out [1,2,3,4]

1 and 5 are both 2 away from 3; the smaller one, 1, wins the tie.

in arr = [1,1,2,3,4,5], k = 4, x = -1

out [1,1,2,3]

x is left of everything, so the first four values are closest.

  • 1 ≤ k ≤ arr.length ≤ 10⁴
  • arr is sorted in ascending order
  • −10⁴ ≤ arr[i], x ≤ 10⁴

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #973
    2. #35
      Search Insert Position
      Easyin Binary Search
    3. #167