LeetCode 658, Medium. Topics: Array, Two Pointers, Binary Search, Sliding Window, Sorting, Heap (Priority Queue). View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:
Problem
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
Examples
Constraints
1 <= k <= arr.length
1 <= arr.length <= 10^4
arr is sorted in ascending order.
-10^4 <= arr[i], x <= 10^4
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
Grind, NeetCode 250, NeetCode All. Last modified on September 7, 2026