Practice › Binary Search
K Closest Elements
Medium · Binary Search · Asked at Meta, Amazon, Google, LinkedIn
The array is sorted. Pick the k elements closest to x and print them in ascending order. Element a is closer than b if |a − x| < |b − x|, or if the distances are equal and a < b.
Input
First line: n k x. Second line: the sorted array.
Output
The k chosen elements in ascending order.
Constraints
- 1 ≤ k ≤ n ≤ 10^5
- −10^4 ≤ values, x ≤ 10^4
The answer is a contiguous window a[i … i + k − 1]. Binary search its start in [0, n − k]: if x − a[mid] > a[mid + k] − x, the window should move right; otherwise left.
Example 1
Input
5 4 3 1 2 3 4 5
Output
1 2 3 4
Example 2
Input
5 4 -1 1 1 2 3 4
Output
1 1 2 3
Hints
- The k closest elements of a sorted array are always a contiguous block.
- Binary search the block’s left end over [0, n − k].
- Compare the element leaving on the left with the one that would enter on the right.
Approach
For a candidate start m, the window is a[m … m + k − 1] and the next alternative is a[m + 1 … m + k]. If x − a[m] > a[m + k] − x, the right element is strictly closer than the left one, so the window must start after m (lo = m + 1); otherwise keep m or move left (hi = m). Ties favour the smaller (left) element, as required. Print a[lo … lo + k − 1].
Complexity: O(log(n − k) + k) time · O(n) space for the input
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
long long x;
cin >> n >> k >> x;
vector<long long> a(n);
for (auto &v : a) cin >> v;
int lo = 0, hi = n - k;
while (lo < hi) {
int m = (lo + hi) / 2;
if (x - a[m] > a[m + k] - x) lo = m + 1;
else hi = m;
}
for (int i = lo; i < lo + k; i++) cout << a[i] << (i + 1 < lo + k ? ' ' : '\n');
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n, k, x = data[0], data[1], data[2]
a = data[3 : 3 + n]
lo, hi = 0, n - k
while lo < hi:
m = (lo + hi) // 2
if x - a[m] > a[m + k] - x:
lo = m + 1
else:
hi = m
print(*a[lo : lo + k])Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int k = (int) in.nval;
in.nextToken();
long x = (long) in.nval;
long[] a = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (long) in.nval;
}
int lo = 0, hi = n - k;
while (lo < hi) {
int m = (lo + hi) / 2;
if (x - a[m] > a[m + k] - x) lo = m + 1;
else hi = m;
}
StringBuilder sb = new StringBuilder();
for (int i = lo; i < lo + k; i++) sb.append(a[i]).append(i + 1 < lo + k ? " " : "\n");
System.out.print(sb);
}
}