Find K Closest Elements solution explained

Find K Closest Elements takes a sorted array, a count k and a target x, and returns the k values closest to x in ascending order, preferring the smaller value when two are equally close. Because the array is sorted, the answer is always a contiguous window of length k, so the task is to find where that window starts. Binary search the start between 0 and n - k by comparing arr[mid] with arr[mid + k], for O(log(n - k) + k) time, or shrink a window from both ends in O(n - k).

By Published 8 min read

Restating the task

You get an array sorted in non-decreasing order, a positive integer k no larger than its length, and an integer x that may or may not appear in the array. Pick k elements whose distance to x, |a - x|, is as small as possible. When two candidates are the same distance away, the smaller one wins. Return the chosen elements in ascending order.

Inputs made up for this page
ArraykxAnswer
[1, 3, 4, 7, 9, 12]36[3, 4, 7]
[2, 4, 6, 8]15[4] (4 and 6 tie; the smaller wins)
[10, 20, 30]20[10, 20]
[1, 1, 2, 2, 2, 3]42[1, 2, 2, 2]
Inputs made up for this page. Scroll sideways on a small screen.

What interviewers want to see

There is an easy answer and a clever one. Sorting by distance works on any array, and saying it first is fine. The point of the question is to notice that the input is already sorted, that the answer must therefore be a contiguous block, and that a block of fixed length is described by one number, its start. Binary searching that start with the right comparison is a good test of careful thinking about ties and duplicates. It is a different problem from K Closest Points to Origin, where the points are unsorted and a heap is the tool.

Baseline: rank by distance

Sort the values by the pair (distance to x, value), keep the first k, and sort those k again to put them in ascending order. The tuple key handles the tie rule for free. It is O(n log n) and ignores the fact that the input was sorted.

def k_closest_by_sorting(arr, k, x):
    ranked = sorted(arr, key=lambda a: (abs(a - x), a))  # distance first, smaller value wins ties
    return sorted(ranked[:k])
Sort by (distance, value). O(n log n). Also the reference the other versions were tested against.

Why the answer is one window

Suppose a value a is in the answer and a value b, sitting between a and x in the array, is not. Because the array is sorted, b lies between a and x on the number line, so it is at least as close to x. If it is strictly closer, swapping a for b improves the answer. If it is exactly as close, a and b must be equal, and the swap changes nothing. So there is always an answer with no gaps, a stretch of k consecutive elements, and the whole answer is decided by where that stretch starts, somewhere from index 0 to index n - k.

Shrink from both ends

Start with the whole array as the window. While it holds more than k values, compare the two ends and drop the one that is farther from x; on a tie, drop the right end, because it holds the larger value. After n - k drops, what remains is the answer.

def k_closest_shrink(arr, k, x):
    lo, hi = 0, len(arr) - 1
    while hi - lo + 1 > k:
        if x - arr[lo] <= arr[hi] - x:    # right end is at least as far: drop it
            hi -= 1
        else:
            lo += 1
    return arr[lo:hi + 1]
Two pointers moving inward. O(n - k) steps plus O(k) to copy the result.

The comparison x - arr[lo] <= arr[hi] - x looks lopsided but is exact for a sorted array. When x lies between the two ends it compares their distances directly. When x is left of both, the left side is negative and the right side is positive, so the right end is dropped, which is correct since it is farther. When x is right of both, the left side is positive and the right side is negative, so the left end is dropped, which is also correct since it is the farther one (or an equal value, which changes nothing).

Binary search the start

Look at a candidate start mid and the window arr[mid .. mid + k - 1]. The element just past it is arr[mid + k]. If arr[mid + k] is strictly closer to x than arr[mid], the window should slide right, so the true start is after mid. Otherwise, sliding right would trade arr[mid] for something no better, so the true start is mid or earlier. That gives a clean yes-or-no condition that flips once across the range, which is all binary search needs.

def find_closest_elements(arr, k, x):
    lo, hi = 0, len(arr) - k              # the window's first index lies in [lo, hi]
    while lo < hi:
        mid = (lo + hi) // 2
        if x - arr[mid] > arr[mid + k] - x:   # arr[mid + k] is strictly closer: start later
            lo = mid + 1
        else:
            hi = mid
    return arr[lo:lo + k]
Binary search on the window's left edge. O(log(n - k) + k) time.

For [1, 3, 4, 7, 9, 12] with k = 3 and x = 6, the start lies in 0..3. At mid = 1 the window's first value 3 and the next value outside it, 9, are both 3 away; not strictly closer, so hi = 1. At mid = 0, the value 1 is 5 away while 7 is 1 away, so lo = 1. The window starts at index 1: [3, 4, 7].

function findClosestElements(arr, k, x) {
  let lo = 0, hi = arr.length - k;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (x - arr[mid] > arr[mid + k] - x) lo = mid + 1;
    else hi = mid;
  }
  return arr.slice(lo, lo + k);
}
JavaScript version of the same search.

The abs() trap

Writing the condition as abs(x - arr[mid]) > abs(arr[mid + k] - x) feels more natural, and it is wrong when the two compared values are equal. Take [2, 2, 2, 5] with k = 1 and x = 5. The answer is [5]. With abs(), mid = 1 compares 2 with 2, sees a tie and keeps the left side; mid = 0 does the same, and the search returns [2]. The signed version notices that x is to the right of both 2s, so x - arr[mid] is 3 while arr[mid + k] - x is -3, and it moves right. If you use the shrink method instead, the same signed comparison is what keeps it correct.

Comparing the approaches

n values, k to return
ApproachTimeExtra space
Sort by (distance, value)O(n log n)O(n)
Max-heap of size kO(n log k)O(k)
Shrink from both endsO(n)O(1) besides the output
Binary search the startO(log(n - k) + k)O(1) besides the output
n values, k to return. Scroll sideways on a small screen.

A third approach finds the insertion point of x with a standard binary search and then grows a window outward with two pointers. It is O(log n + k) and also correct, but the boundary handling is longer to write than the start search.

Test inputs

  • x smaller than every element: the answer is the first k.
  • x larger than every element: the answer is the last k.
  • k equal to n: the whole array.
  • Ties exactly halfway between two values, where the smaller must win.
  • Long runs of duplicates on one side of x, the case that breaks abs().

Pitfalls

  • Using abs() in the binary search condition.
  • Searching starts in 0..n - 1 instead of 0..n - k, then reading past the end at mid + k.
  • Returning the k closest in distance order instead of ascending order.
  • Breaking ties toward the larger value.
  • Using a heap and forgetting that the input was sorted, which the interviewer will ask about.

A spoken version

Fictional example

Reducing it to one index
Candidate
The array is sorted, so the k closest values have to be next to each other. I only need to find where that block of k starts, between 0 and n minus k.
Candidate
For a start mid, I compare the first value in the window with the first one after it. If the one after is strictly closer, the window belongs further right.
Interviewer
Why not compare absolute distances?
Candidate
If both values are equal and on the same side of x, abs makes them look tied even though the window should move. Comparing x minus left with right minus x keeps the direction. Total cost is log of n minus k, plus k to copy.

Capacity to Ship Packages Within D Days and Split Array Largest Sum binary search a value rather than a position. Minimum Number of Arrows to Burst Balloons and The Skyline Problem are sorting-first problems on ranges. For the unsorted cousin, see K Closest Points to Origin and Kth Largest Element in an Array.

Practice support from Natively

The tie rule and the signed comparison are where this problem is won or lost, so practise explaining them. In a practice session on a Mac or a Windows PC, Natively can read the problem from a screenshot and show an approach and code in its overlay, which you can test against the duplicate cases on this page. If you speak your reasoning during a mock round, its transcript lets you check whether you explained why the answer is one window. Learn more about the AI interview assistant.

Questions people ask

How do you solve Find K Closest Elements?

Binary search the window start between 0 and n - k. At mid, if arr[mid + k] is strictly closer to x than arr[mid], move right; otherwise keep mid as a candidate. Return arr[lo:lo + k].

What is the time complexity of Find K Closest Elements?

O(log(n - k) + k) with the binary search on the start, O(n) with two pointers shrinking the window, and O(n log n) by sorting on distance.

Why not use abs() in the Find K Closest Elements binary search?

When arr[mid] and arr[mid + k] are equal values on the same side of x, abs() reports a tie and the window does not move, which can return the wrong values. Compare x - arr[mid] with arr[mid + k] - x instead.

How are ties handled in Find K Closest Elements?

When two values are equally far from x, the smaller value is preferred, and the result is returned in ascending order.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP