Skip to main content
Back to problems
#658
Medium Algorithms

Find k closest elements

Array Two Pointers Binary Search Sliding Window Sorting Heap (Priority Queue)
49.4% acceptance
Feb 20, 2026
9008
907
Given a sorted integer array arr and two integers k and x, return the k closest integers to x in the array. Result should be sorted in ascending order. If two integers are equally close, choose the smaller one.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn find_closest_elements(arr: Vec<i32>, k: i32, x: i32) -> Vec<i32> {
    let k = k as usize;
    let n = arr.len();
    let mut lo = 0usize;
    let mut hi = n - k;
    while lo < hi {
      let mid = (lo + hi) / 2;
      if x - arr[mid] > arr[mid + k] - x {
        lo = mid + 1;
      } else {
        hi = mid;
      }
    }
    arr[lo..lo + k].to_vec()
  }
}