658. Find K Closest Elements
Asked at 17Apple46Amazon45Meta45Google38Microsoft35Bloomberg25Yandex83Coupang76Cashfree66DoorDash66Capgemini52Flipkart43LinkedIn40DE Shaw38Salesforce28TikTok26Uber22
Problem
arr is sorted. Return the k values closest to x, sorted ascending. a is closer than b if |a − x| < |b − x|, or if the distances are equal and a < b.
Example: arr = [1,2,3,4,5], k = 4, x = 3 → [1,2,3,4]
Constraints: n ≤ 10⁴.
The answer is a window arr[i .. i+k). Binary search its start i ∈ [0, n−k]: if x − arr[mid] > arr[mid+k] − x, the window should move right.
Complexity: O(log(n − k) + k).
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
lo, hi = 0, len(arr) - k
while lo < hi:
mid = (lo + hi) // 2
if x - arr[mid] > arr[mid + k] - x:
lo = mid + 1
else:
hi = mid
return arr[lo:lo + k]
assert Solution().findClosestElements([1, 2, 3, 4, 5], 4, 3) == [1, 2, 3, 4]
assert Solution().findClosestElements([1, 1, 2, 3, 4, 5], 4, -1) == [1, 1, 2, 3]
assert Solution().findClosestElements([1, 3], 1, 2) == [1]
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
int lo = 0, hi = arr.length - k;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (x - arr[mid] > arr[mid + k] - x) lo = mid + 1; else hi = mid;
}
List<Integer> res = new ArrayList<>();
for (int i = lo; i < lo + k; i++) res.add(arr[i]);
return res;
}
}
func findClosestElements(arr []int, k int, x int) []int {
lo, hi := 0, len(arr)-k // left end of the window
for lo < hi {
mid := (lo + hi) / 2
if x-arr[mid] > arr[mid+k]-x { // arr[mid+k] is closer: move right
lo = mid + 1
} else {
hi = mid
}
}
return arr[lo : lo+k]
}