Find K Closest Elements

Medium

Topics
ArrayBinary SearchTwo PointersSortingHeap

nums is sorted ascending. Return the k elements closest to x, in ascending order.

Closeness is |value - x|. When two values are equally close, the smaller one is preferred.

LeetCode names the first argument arr; the harness here calls it nums.

Example 1

nums1021324354the answer
distance from 321012
in the answerdropped
Measured against x = 3, the 4 closest values form the braced stretch. The answer is always contiguous: if two values are in it, anything between them is no further from x than the further of the two, so it belongs as well and a gap is never needed. Here 1 and 5 are equally far, and only one fits — the rule keeps the smaller.
The answer comes back ascending by value, not ordered by distance.
Input:  nums = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Explanation: 1 and 5 are both 2 away from 3, and only one of them fits — the smaller, so 1 is kept and 5 is dropped.

Example 2

nums1021324354the answer
distance from -123456
in the answerdropped
No two values here are equally far from x, so the smaller-value tie-break never has to be applied.
Input:  nums = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]
Explanation: x sits below everything, so the closest k are simply the first k.

Example 3

nums101112103104105the answer
distance from 9888111
in the answerdropped
Measured against x = 9, the 1 closest value form the braced stretch.
Input:  nums = [1,1,1,10,10,10], k = 1, x = 9
Output: [10]
Explanation: 10 is 1 away and 1 is 8 away, so duplicates on the far side change nothing.

Constraints

  • 1 <= k <= nums.length
  • 1 <= nums.length <= 10^4
  • nums is sorted ascending
  • -10^4 <= nums[i], x <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

The result is a contiguous window of the array, and seeing that is most of the problem. The values are sorted, so the k closest to x cannot have a gap in the middle: if two values are in the answer, everything between them is at least as close as the further of the two, so it belongs as well.

So the question is not "which k values" but "where does the window of width k start". That is one number between 0 and len(nums) - k.

Sorting by distance and taking the first k also works, and it throws away the sortedness that makes the problem interesting. It also needs care: the tie rule is by value, not by position, so the comparison has to be distance first and then value.

To locate the window directly, compare the two values that would be dropped by moving the window one step right: the one at the left edge and the one just past the right edge. If the value past the right edge is strictly closer to x, the window should move. Phrasing the comparison as x - nums[mid] > nums[mid + k] - x handles the tie correctly for free, because a tie fails the strict test and the window stays left — which is exactly the smaller-value preference.

Approach

  1. The answer is nums[start .. start + k - 1] for some start in [0, len(nums) - k].
  2. Search for start over that range. At a candidate mid, compare x - nums[mid] against nums[mid + k] - x.
  3. If the left-edge value is strictly further from x than the first value outside the window, the start must be greater than mid.
  4. Otherwise the start is mid or less. A tie keeps the window where it is, which is what prefers the smaller value.
  5. Return the k values beginning at the start that the search settles on; they are already ascending.

Walkthrough

nums = [1,2,3,4,5], k = 4, x = 3

the answer is a window of width 4, so start is 0 or 1

   start 0 -> [1,2,3,4]
   start 1 -> [2,3,4,5]

which one? compare the value dropped by moving right
   moving from 0 to 1 drops nums[0] = 1 and gains nums[4] = 5
   |1 - 3| = 2        |5 - 3| = 2
   a tie, and the rule prefers the smaller value, so KEEP 1
   start stays 0

answer [1,2,3,4]

x = -1 on the same array
   moving from 0 to 1 drops 1 and gains 5
   |1 - (-1)| = 2     |5 - (-1)| = 6
   1 is closer, so do not move
   answer [1,2,3,4]

why the answer has to be contiguous
   suppose 2 and 4 are both in the answer but 3 is not.
   3 lies between them, so it is no further from x than
   whichever of 2 and 4 is further -- so swapping it in
   never makes the answer worse. A gap is never required.

Complexity

  • Time — O(log(n - k) + k): the search is over start positions; copying the window out is the k.
  • Space — O(k): the output.

Common Pitfalls

  • Breaking ties by position instead of by value. The smaller value wins, which on a sorted array means the left one.
  • Using >= in the comparison, which moves the window on a tie and returns the larger value.
  • Searching over the whole array rather than over start positions, so the window can run off the end.
  • Sorting by distance and then returning in that order. The result has to come back ascending by value.
  • Assuming x is inside the array’s range. It can sit below everything or above everything, and then the answer is just the first or last k.

Full Solution — all languages

class Solution:
    def findClosestElements(self, nums, k, x):
        # The answer is a window of width k; search for where it starts.
        lo, hi = 0, len(nums) - k

        while lo < hi:
            mid = (lo + hi) // 2

            # Compare the value the window would drop against the one it
            # would gain. A tie fails this strict test, so the window stays
            # left -- which is the smaller-value preference.
            if x - nums[mid] > nums[mid + k] - x:
                lo = mid + 1
            else:
                hi = mid

        return nums[lo:lo + k]
SensAI
Beta
Tap the mic to stop voice mode