Heap / Priority Queue
Medium
Find K Closest Elements
Find k closest integers to a given value x.
10 min read
Solve on LeetCodeProblem Understanding
Given a sorted integer array arr, two integers k and x, return the k closest integers to x.
If |a - x| == |b - x|, the smaller number is chosen. The internal array must be sorted.
Example:
- Input:
arr = [1,2,3,4,5],k = 4,x = 3 - Output:
[1,2,3,4]
Algorithm Strategy
Approach 1: Max-Heap (Standard Top-K)
Similar to previous problems, maintain a Max-Heap of size K.
- Priority is distance
|val - x|. - Pop the element with the largest distance if size > K.
Approach 2: Two Pointers (Optimal for Sorted Input)
Since the array is sorted, the K closest elements will be a contiguous subarray.
- Use Binary Search to find the closest element to
x. - Expand Left and Right pointers to collect K neighbours.
Interactive Visualization
Step 1 / 1
Empty Heap
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run (Two Pointers)
- Edge Cases
- Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
