Skip to content
Problem 658 · LeetCode 658(opens in a new tab)

Find K Closest Elements

MediumArrays

You get an array arr sorted from small to large, and two numbers k and x. Return the k values of arr that are closest to x, sorted from small to large.

A value a is closer to x than a value b when |a − x| < |b − x|. When the two distances are equal, the smaller value counts as closer.

Example 1

Input:  arr = [2, 4, 5, 7, 9, 12], k = 3, x = 8
Output: [5, 7, 9]
Why:    7 and 9 are 1 away, 5 is 3 away; 4 and 12 are 4 away
2 more examples and the constraints

Example 2

Input:  arr = [1, 3, 3, 6], k = 2, x = 0
Output: [1, 3]
Why:    x is below everything, so the smallest values win

Example 3

Input:  arr = [3, 5, 7, 9], k = 1, x = 6
Output: [5]
Why:    5 and 7 are both 1 away; the smaller one wins

Constraints

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

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort by distanceO(n log n)
  2. Shrink from both endsO(n − k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 values and small kVerdict
Sort by distanceO(n log n)
Simple; ignores the sorted input
Shrink from both endsO(n − k)
Linear and easy to explain
Binary search for the startO(log n + k)
Best; only reads what it needs

n = length of arr, k = values to return.

Edge cases to test

  • x outside the range. Below every value the answer is the first k values; above every value it is the last k.
  • Ties. In [3, 5, 7, 9] with x = 6 and k = 1, 5 and 7 are both 1 away and 5 must win.
  • k equals the length. Return the whole array; the binary search starts with lo = hi = 0.
  • Duplicates. Equal values count as separate elements. In [0, 0, 0, 4] with k = 1 and x = 3 the answer is [4], which a binary search using abs() misses.

Common mistakes

  • Comparing with abs() in the binary search, which stalls on equal values that both lie below x.
  • Dropping the left end on a tie in the two-pointer version, which keeps the larger value.
  • Setting hi = n − 1 instead of n − k, so arr[mid + k] runs off the end.

How to talk through it

  1. 1Clarify. Is the output sorted by value? How are ties broken? Can x be outside the array's range?
  2. 2Start simple. Sort by distance, take k, sort back: O(n log n), and it ignores that the input is sorted.
  3. 3Use the order. The answer is a contiguous block, so the farthest value is always at an end: shrink from both sides in O(n − k).
  4. 4Search the start. Only the window's start is unknown. Comparing arr[mid] with arr[mid + k] tells me which way to go.
  5. 5Test out loud. Run x below everything, x above everything, and a tie between two neighbours.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?