Find K Closest Elements Problem
Description
LeetCode Problem 658.
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:
- |a - x| < |b - x|, or
- |a - x| == |b - x| and a < b
Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Example 2:
Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]
Constraints:
- 1 <= k <= arr.length
- 1 <= arr.length <= 10^4
- arr is sorted in ascending order.
- -10^4 <= arr[i], x <= 10^4
Solution
Approach: Binary Search for the Window's Start
Because arr is sorted, the k closest elements always form a contiguous window arr[left .. left + k - 1]. Instead of searching for x and expanding outward, we binary search directly for left, which lies in [0, n - k].
Compare a candidate start mid with the window one step to the right. Moving from arr[mid .. mid + k - 1] to arr[mid + 1 .. mid + k] drops arr[mid] and adds arr[mid + k]:
- If
x - arr[mid] > arr[mid + k] - x, thenarr[mid + k]is strictly closer thanarr[mid], so the best window starts aftermid: setleft = mid + 1. - Otherwise
arr[mid]is at least as good (a tie goes to the smaller value), so the best start ismidor earlier: setright = mid.
When left == right, return arr[left .. left + k - 1].
The detail that matters is comparing x - arr[mid] with arr[mid + k] - x without abs. If arr[mid] and arr[mid + k] are equal and both below x, absolute values call it a tie and stop moving right, even though closer values may lie further right. For arr = [1,1,2,2,2,2,2,3,3], k = 3, x = 3 that returns [2,2,2] instead of [2,3,3]. The signed comparison (1 > -1) correctly slides the window right.
Complexity: O(log(n − k) + k) time, where n is the length of arr: the binary search plus copying the window. O(1) extra space besides the output.
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# Binary search for the start of the best window arr[left : left + k].
left, right = 0, len(arr) - k
while left < right:
mid = (left + right) // 2
# arr[mid + k] is closer than arr[mid]: the window should start after mid.
if x - arr[mid] > arr[mid + k] - x:
left = mid + 1
else:
right = mid
return arr[left:left + k]