Find K Closest Elements

35 min · findClosestElements()

A sorted price list can contain 100,000 entries, yet a shopper may want only the k prices nearest a budget x. Sorting those prices by closeness would throw away the most useful fact you were given: they're already in order.

Given a non-decreasing integer array arr, return the k values closest to x. Return those values in ascending order.

Value a is closer than value b when:

  • |a - x| < |b - x|, or
  • the distances tie and a < b.

The answer always forms a contiguous window, meaning one uninterrupted slice of arr. Duplicate values are allowed and occupy separate positions.

Constraints

  • 1 <= k <= arr.length <= 100_000
  • arr is sorted in non-decreasing order.
  • -1_000_000_000 <= arr[i], x <= 1_000_000_000

Hints

Remove what can't survive

Compare the two endpoints. Whichever endpoint is farther from x can't belong to the final window. On a tie, remove the larger right endpoint.

Search for a window, not a value

A size-k answer can start only from index 0 through arr.length - k. Binary-search that range for the first valid left edge.

Compare neighboring windows

For a window starting at mid, compare x - arr[mid] with arr[mid + k] - x. If the left value is farther, shift the window right. A tie stays left because the smaller value wins.

Follow-up

Can you explain why the closest values must be contiguous before writing either solution? That proof is the reason binary search is available here.

Visible cases

Examples

Example 1

ready
Input
arr = [
  1,
  2,
  3,
  4,
  5
]
k = 4
x = 3
Expected
[
  1,
  2,
  3,
  4
]
Why
1 and 5 tie in distance, so the smaller value 1 stays

Example 2

ready
Input
arr = [
  1,
  2,
  3,
  4,
  5
]
k = 4
x = -1
Expected
[
  1,
  2,
  3,
  4
]
Why
x lies below every value, so the four smallest are closest

Example 3

ready
Input
arr = [
  1,
  2,
  3,
  4,
  5
]
k = 4
x = 6
Expected
[
  2,
  3,
  4,
  5
]
Why
x lies above every value, so the four largest are closest

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite