658. Find K Closest Elements
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find k integers in a sorted array arr that are closest to a given value x. The result must also be sorted. A crucial observation is that since the input array arr is sorted, the k closest elements will form a contiguous subarray of arr. Why? If the result set was not contiguous, say it included arr[i] and arr[j] but not arr[p] where i < p < j, we could likely find a better set by replacing a faraway element with arr[p]. This property simplifies the problem: instead of picking k arbitrary elements, we just need to find the best contiguous block of size k.
Solution
Find K Closest Elements in Python
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
n = len(arr)
# The result is a contiguous subarray of size k.
# We are looking for its start index.
# The possible start indices are from 0 to n - k.
low = 0
high = n - k
# Binary search to find the optimal starting index.
while low < high:
mid = low + (high - low) // 2
# For a window starting at `mid`, arr[mid...mid+k-1], the element to its right
# that could be included is arr[mid+k].
# We compare arr[mid] with arr[mid+k].
# If x is closer to arr[mid+k] than arr[mid], it's better to shift our window
# to the right, so the start should be at least mid + 1.
# `x` is closer to `arr[mid+k]` than `arr[mid]` if `x` is greater than their midpoint.
# This also correctly handles ties: if equidistant, `x` is the midpoint, the condition
# is false, and we prefer `arr[mid]` (the smaller element).
if x - arr[mid] > arr[mid + k] - x:
low = mid + 1
else:
high = mid
# At the end of the loop, `low` is the optimal starting index.
return arr[low : low + k]
Find K Closest Elements in Java
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
int n = arr.length;
// The result is a contiguous subarray of size k.
// We are looking for its start index.
// The possible start indices are from 0 to n - k.
int low = 0;
int high = n - k;
// Binary search to find the optimal starting index.
while (low < high) {
int mid = low + (high - low) / 2;
// For a window starting at `mid`, arr[mid...mid+k-1], the element to its right
// that could be included is arr[mid+k].
// We compare arr[mid] with arr[mid+k].
// If x is closer to arr[mid+k] than arr[mid], it's better to shift our window
// to the right, so the start should be at least mid + 1.
// `x` is closer to `arr[mid+k]` than `arr[mid]` if `x` is greater than their midpoint.
// This also correctly handles ties: if equidistant, `x` is the midpoint, the condition
// is false, and we prefer `arr[mid]` (the smaller element).
if (x - arr[mid] > arr[mid + k] - x) {
low = mid + 1;
} else {
high = mid;
}
}
// At the end of the loop, `low` is the optimal starting index.
List<Integer> result = new ArrayList<>(k);
for (int i = 0; i < k; i++) {
result.add(arr[low + i]);
}
return result;
}
}
Find K Closest Elements in C++
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int n = arr.size();
// The result is a contiguous subarray of size k.
// We are looking for its start index.
// The possible start indices are from 0 to n - k.
int low = 0;
int high = n - k;
// Binary search to find the optimal starting index.
while (low < high) {
int mid = low + (high - low) / 2;
// For a window starting at `mid`, arr[mid...mid+k-1], the element to its right
// that could be included is arr[mid+k].
// We compare arr[mid] with arr[mid+k].
// If x is closer to arr[mid+k] than arr[mid], it's better to shift our window
// to the right, so the start should be at least mid + 1.
// `x` is closer to `arr[mid+k]` than `arr[mid]` if `x` is greater than their midpoint.
// This also correctly handles ties: if equidistant, `x` is the midpoint, the condition
// is false, and we prefer `arr[mid]` (the smaller element).
if (x - arr[mid] > arr[mid + k] - x) {
low = mid + 1;
} else {
high = mid;
}
}
// At the end of the loop, `low` is the optimal starting index.
return vector<int>(arr.begin() + low, arr.begin() + low + k);
}
};
Find K Closest Elements in TypeScript
function findClosestElements(arr: number[], k: number, x: number): number[] {
const n = arr.length;
// The result is a contiguous subarray of size k.
// We are looking for its start index.
// The possible start indices are from 0 to n - k.
let low = 0;
let high = n - k;
// Binary search to find the optimal starting index.
while (low < high) {
const mid = low + Math.floor((high - low) / 2);
// For a window starting at `mid`, arr[mid...mid+k-1], the element to its right
// that could be included is arr[mid+k].
// We compare arr[mid] with arr[mid+k].
// If x is closer to arr[mid+k] than arr[mid], it's better to shift our window
// to the right, so the start should be at least mid + 1.
// `x` is closer to `arr[mid+k]` than `arr[mid]` if `x` is greater than their midpoint.
// This also correctly handles ties: if equidistant, `x` is the midpoint, the condition
// is false, and we prefer `arr[mid]` (the smaller element).
if (x - arr[mid] > arr[mid + k] - x) {
low = mid + 1;
} else {
high = mid;
}
}
// At the end of the loop, `low` is the optimal starting index.
return arr.slice(low, low + k);
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.