Skip to content

Find K Closest Elements

MediumBinary Search
Decode it first. Clues, constraints, pattern and plan before any code.

Given a sorted list arr, an integer k and a value x, return the k values in arr that are closest to x, in ascending order. Value a is closer than b when |a - x| < |b - x|, or when they tie and a < b.

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

Constraints

  • 1 <= k <= arr.length <= 10^4
  • -10^4 <= arr[i], x <= 10^4
  • arr is sorted in ascending order.