Find K Closest Elements - Problem
Given a sorted integer array
An integer
โข
โข
Example: For 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 considered closer to x than integer b if:โข
|a - x| < |b - x| (smaller absolute difference), orโข
|a - x| == |b - x| and a < b (same distance but smaller value)Example: For array
[1,2,3,4,5], k=4, and x=3, the answer is [1,2,3,4] because these are the 4 numbers closest to 3. Input & Output
example_1.py โ Basic case
$
Input:
arr = [1,2,3,4,5], k = 4, x = 3
โบ
Output:
[1,2,3,4]
๐ก Note:
The 4 closest elements to 3 are 1, 2, 3, and 4. Distance from 3: |1-3|=2, |2-3|=1, |3-3|=0, |4-3|=1, |5-3|=2. Taking the 4 smallest distances gives us [1,2,3,4].
example_2.py โ Tie-breaking case
$
Input:
arr = [1,2,3,4,5], k = 4, x = -1
โบ
Output:
[1,2,3,4]
๐ก Note:
When x=-1, all elements are on the right side. Distances: |1-(-1)|=2, |2-(-1)|=3, |3-(-1)|=4, |4-(-1)|=5, |5-(-1)|=6. The 4 closest are still [1,2,3,4].
example_3.py โ Single element
$
Input:
arr = [1,2,3,4,5], k = 1, x = 3
โบ
Output:
[3]
๐ก Note:
When k=1, we only need the single closest element to x=3, which is 3 itself with distance 0.
Visualization
Tap to expand
Understanding the Visualization
1
Position Yourself
You stand at x=3 on the number line
2
Measure Distances
Calculate how far each friend is from your position
3
Find Optimal Window
Since friends are in a line, your k closest friends will be consecutive
4
Select the Group
Choose the contiguous group of k friends with minimal total distance
Key Takeaway
๐ฏ Key Insight: Since the array is sorted, the k closest elements always form a contiguous subarray, enabling O(log n) binary search instead of O(n log n) sorting!
Time & Space Complexity
Time Complexity
O(n)
Single pass through array with two pointers, O(n-k) iterations maximum
โ Linear Growth
Space Complexity
O(1)
Only uses constant extra space for pointers
โ Linear Space
Constraints
- 1 โค k โค arr.length
- 1 โค arr.length โค 104
- arr is sorted in ascending order
- -104 โค arr[i], x โค 104
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code