Find K Closest Elements
Problem Statement
You get a sorted array arr (smallest to largest), plus two numbers: k and x. Return the k values in arr that are closest to x.
A value is closer to x when |value − x| is smaller. If two values are equally close, the smaller value wins. Return the answer sorted from smallest to largest.
arr, a sorted list of integers. k, how many values to return. x, the number to compare against.
The k closest values, sorted in ascending order.
The distances to 3 are 2, 1, 0, 1, 2. The first three picks are 3, 2 and 4. Then 1 and 5 tie at distance 2, so the smaller one, 1, wins.
Every value is to the right of −1, so the closest values are the smallest ones. The answer is the first four.
- • 1 ≤ k ≤ arr.length
- • 1 ≤ arr.length ≤ 10^4
- • arr is sorted in ascending order
- • −10^4 ≤ arr[i], x ≤ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Sort a copy by (distance, value), keep k, then sort those k values
Keep the k closest values in a max-heap; sort the k values at the end
The answer is one block of k neighbours, so binary search where that block starts
Sort a copy of arr with the rule from the question: sort by distance to x, then by value. Keep the first k values, and sort those k values again so they come out in ascending order.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Heap — Top K translate into production architectures and low-level memory mechanics.