VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-k-closest-elements-given-value/

⇱ Closest K Elements in a Sorted Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Closest K Elements in a Sorted Array

Last Updated : 11 Jun, 2025

You are given a sorted array arr[] containing unique integers, a number k, and a target value x. Your goal is to return exactly k elements from the array that are closest to x, excluding x itself if it is present in the array.

An element a is closer to x than b if:

  • |a - x| < |b - x|, or
  • |a - x| == |b - x| and a > b (i.e., prefer the larger element if tied)

Examples:

Input: arr[] = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56], k = 4, x = 35
Output: 39 30 42 45
Explanation: First closest element to 35 is 39.
Second closest element to 35 is 30.
Third closest element to 35 is 42.
And fourth closest element to 35 is 45.

Input: arr[] = [1, 3, 4, 10, 12], k = 2, x = 4
Output: 3 1
Explanation:4 is excluded, Closest elements to 4 are: 3 (1), 1 (3). So, the 2 closest elements are: 3 1

[Naive Aprroach] Using Absolute difference and Custom Sorting O(n*log(n)) Time and O(k) Space

The idea is to use the absolute difference between each element and the target value to measure how close they are. Then, we apply custom sorting: elements with smaller differences come first, and in case of a tie, the larger element is preferred. we take the k element from get from custrom sorted array then return it.


Output
39 30 42 45 

[Better Approach] Using Linear Search- O(n) time and O(k) space

The idea is to first go through the array to find the last element that is less than or equal to the target value, skipping the target if it's present. Then, we use two pointers to choose the k closest elements by comparing their differences, while following the tie-breaking rules.


Output
39 30 42 45 

[Expected Approach] Using Binary Search - O(k + log n) time and O(k) space

The idea is to first use binary search to quickly find the last element in the array that is less than or equal to the target (skipping the target itself if it exists). Then, we use a two-pointer approach to select the k closest elements, following the tie-breaking rules.


Output
39 30 42 45 
Comment
Article Tags: