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.
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
// Function to return k closest elements to x
vector<int> printKClosest(vector<int> &arr, int k, int x) {
// Custom comparator using absolute difference and tie-breaker
sort(arr.begin(), arr.end(), [x](int a, int b) {
int diffA = abs(a - x);
int diffB = abs(b - x);
// If differences are equal, prefer the larger element
if (diffA == diffB)
return a > b;
return diffA < diffB;
});
vector<int> result;
int count = 0;
// Pick first k elements which are not equal to x
for (int num : arr) {
// skip if element is equal to x
if (num == x) continue;
result.push_back(num);
count++;
if (count == k)
break;
}
return result;
}
// Main function with example
int main() {
vector<int> arr = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56};
int k = 4;
int x = 35;
vector<int> closest = printKClosest(arr, k, x);
for (int num : closest) {
cout << num << " ";
}
return 0;
}
Java
import java.util.*;
public class Main {
// Function to return k closest elements to x
public static int[] printKClosest(int[] arr, int k, int x) {
// Convert array to list for easier sorting with custom comparator
List<Integer> list = new ArrayList<>();
for (int num : arr) {
list.add(num);
}
// Custom sort using absolute difference and tie-breaking
list.sort((a, b) -> {
int diffA = Math.abs(a - x);
int diffB = Math.abs(b - x);
if (diffA == diffB) {
// prefer larger element
return b - a;
}
return diffA - diffB;
});
List<Integer> result = new ArrayList<>();
int count = 0;
// Pick first k elements not equal to x
for (int num : list) {
// skip if element is equal to x
if (num == x) continue;
result.add(num);
count++;
if (count == k) break;
}
// Convert list to array
int[] closest = new int[k];
for (int i = 0; i < k; i++) {
closest[i] = result.get(i);
}
return closest;
}
// Main function with example
public static void main(String[] args) {
int[] arr = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56};
int k = 4;
int x = 35;
int[] closest = printKClosest(arr, k, x);
for (int num : closest) {
System.out.print(num + " ");
}
}
}
Python
def printKClosest(arr, k, x):
# Custom sort using absolute difference and tie-breaking
# -a to prefer larger on tie
arr.sort(key=lambda a: (abs(a - x), -a))
result = []
count = 0
# Pick first k elements not equal to x
for num in arr:
if num == x:
continue # skip if element is equal to x
result.append(num)
count += 1
if count == k:
break
return result
if __name__ == "__main__":
arr = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56]
k = 4
x = 35
closest = printKClosest(arr, k, x)
print( *closest)
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
// Function to return k closest elements to x
public static int[] printKClosest(int[] arr, int k, int x){
// Convert to list for sorting with custom comparator
List<int> list = arr.ToList();
// Custom sort using absolute difference and tie-breaking
list.Sort((a, b) => {
int diffA = Math.Abs(a - x);
int diffB = Math.Abs(b - x);
if (diffA == diffB)
// prefer larger element
return b - a;
return diffA - diffB;
});
List<int> result = new List<int>();
int count = 0;
// Pick first k elements not equal to x
foreach (int num in list){
// skip if element is equal to x
if (num == x) continue;
result.Add(num);
count++;
if (count == k) break;
}
return result.ToArray();
}
// Main function with example
static void Main(){
int[] arr = { 12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56 };
int k = 4;
int x = 35;
int[] closest = printKClosest(arr, k, x);
foreach (int num in closest){
Console.Write(num + " ");
}
}
}
JavaScript
function printKClosest(arr, k, x) {
// Custom sort using absolute difference and tie-breaking
arr.sort((a, b) => {
let diffA = Math.abs(a - x);
let diffB = Math.abs(b - x);
if (diffA === diffB) return b - a; // prefer larger element
return diffA - diffB;
});
let result = [];
let count = 0;
// Pick first k elements not equal to x
for (let num of arr) {
if (num === x) continue;
result.push(num);
count++;
if (count === k) break;
}
return result;
}
// Cotume code
let arr = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56];
let k = 4;
let x = 35;
let closest = printKClosest(arr, k, x);
console.log(...closest);
[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.
C++
// C++ program to find k closest elements to a given value
#include <bits/stdc++.h>
using namespace std;
// Function to find k closest elements to a given value
vector<int> printKClosest(vector<int> &arr, int k, int x) {
int n = arr.size();
int i = 0;
// Find index of element just less than x
while (i < n && arr[i] < x) i++;
int left = i - 1, right = i;
// If value at right index is x, increment
if (arr[right] == x) right++;
vector<int> res;
while (left >=0 && right < n && res.size() < k) {
int leftDiff = abs(arr[left] - x);
int rightDiff = abs(arr[right] - x);
if (leftDiff < rightDiff) {
res.push_back(arr[left]);
left--;
}
else {
res.push_back(arr[right]);
right++;
}
}
// If k elements are not filled
while (left >=0 && res.size() < k) {
res.push_back(arr[left]);
left--;
}
while (right < n && res.size() < k) {
res.push_back(arr[right]);
right++;
}
return res;
}
int main() {
vector<int> arr =
{12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56};
int k = 4, x = 35;
vector<int> res = printKClosest(arr, k, x);
for (int val: res) cout << val << " ";
cout << endl;
return 0;
}
Java
// Java program to find k closest elements to a given value
class GfG {
// Function to find k closest elements to a given value
static int[] printKClosest(int[] arr, int k, int x) {
int n = arr.length;
int i = 0;
// Find index of element just less than x
while (i < n && arr[i] < x) i++;
int left = i - 1, right = i;
// If value at right index is x, increment
if (right < n && arr[right] == x) right++;
int[] res = new int[k];
int count = 0;
while (left >= 0 && right < n && count < k) {
int leftDiff = Math.abs(arr[left] - x);
int rightDiff = Math.abs(arr[right] - x);
if (leftDiff < rightDiff) {
res[count++] = arr[left];
left--;
}
else {
res[count++] = arr[right];
right++;
}
}
// If k elements are not filled
while (left >= 0 && count < k) {
res[count++] = arr[left];
left--;
}
while (right < n && count < k) {
res[count++] = arr[right];
right++;
}
return res;
}
public static void main(String[] args) {
int[] arr =
{12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56};
int k = 4, x = 35;
int[] res = printKClosest(arr, k, x);
for (int val : res) System.out.print(val + " ");
System.out.println();
}
}
Python
# Python program to find k closest elements to a given value
# Function to find k closest elements to a given value
def printKClosest(arr, k, x):
n = len(arr)
i = 0
# Find index of element just less than x
while i < n and arr[i] < x:
i += 1
left = i - 1
right = i
# If value at right index is x, increment
if right < n and arr[right] == x:
right += 1
res = []
while left >= 0 and right < n and len(res) < k:
leftDiff = abs(arr[left] - x)
rightDiff = abs(arr[right] - x)
if leftDiff < rightDiff:
res.append(arr[left])
left -= 1
else:
res.append(arr[right])
right += 1
# If k elements are not filled
while left >= 0 and len(res) < k:
res.append(arr[left])
left -= 1
while right < n and len(res) < k:
res.append(arr[right])
right += 1
return res
if __name__ == "__main__":
arr = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56]
k = 4
x = 35
res = printKClosest(arr, k, x)
print(' '.join(map(str, res)))
C#
// C# program to find k closest elements to a given value
using System;
class GfG {
// Function to find k closest elements to a given value
static int[] printKClosest(int[] arr, int k, int x) {
int n = arr.Length;
int i = 0;
// Find index of element just less than x
while (i < n && arr[i] < x) i++;
int left = i - 1, right = i;
// If value at right index is x, increment
if (right < n && arr[right] == x) right++;
int[] res = new int[k];
int count = 0;
while (left >= 0 && right < n && count < k) {
int leftDiff = Math.Abs(arr[left] - x);
int rightDiff = Math.Abs(arr[right] - x);
if (leftDiff < rightDiff) {
res[count++] = arr[left];
left--;
}
else {
res[count++] = arr[right];
right++;
}
}
// If k elements are not filled
while (left >= 0 && count < k) {
res[count++] = arr[left];
left--;
}
while (right < n && count < k) {
res[count++] = arr[right];
right++;
}
return res;
}
static void Main() {
int[] arr =
{12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56};
int k = 4, x = 35;
int[] res = printKClosest(arr, k, x);
foreach (int val in res) Console.Write(val + " ");
Console.WriteLine();
}
}
JavaScript
// JavaScript program to find k closest elements to a given value
// Function to find k closest elements to a given value
function printKClosest(arr, k, x) {
let n = arr.length;
let i = 0;
// Find index of element just less than x
while (i < n && arr[i] < x) i++;
let left = i - 1, right = i;
// If value at right index is x, increment
if (right < n && arr[right] === x) right++;
let res = [];
while (left >= 0 && right < n && res.length < k) {
let leftDiff = Math.abs(arr[left] - x);
let rightDiff = Math.abs(arr[right] - x);
if (leftDiff < rightDiff) {
res.push(arr[left]);
left--;
}
else {
res.push(arr[right]);
right++;
}
}
// If k elements are not filled
while (left >= 0 && res.length < k) {
res.push(arr[left]);
left--;
}
while (right < n && res.length < k) {
res.push(arr[right]);
right++;
}
return res;
}
let arr = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56];
let k = 4, x = 35;
let res = printKClosest(arr, k, x);
console.log(res.join(' '));
[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.
C++
// C++ program to find k closest elements to a given value
#include <bits/stdc++.h>
using namespace std;
// Function to find k closest elements to a given value
vector<int> printKClosest(vector<int> &arr, int k, int x) {
int n = arr.size();
int i = 0;
int low = 0, high = n - 1, pos = -1;
// Binary search to find last element less than x
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] < x) {
pos = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
int left = pos, right = pos + 1;
// If value at right index is x, increment
if (arr[right] == x) right++;
vector<int> res;
// Use two-pointer technique to pick k closest elements
while (left >=0 && right < n && res.size() < k) {
int leftDiff = abs(arr[left] - x);
int rightDiff = abs(arr[right] - x);
if (leftDiff < rightDiff) {
res.push_back(arr[left]);
left--;
}
else {
res.push_back(arr[right]);
right++;
}
}
// If k elements are not filled
while (left >=0 && res.size() < k) {
res.push_back(arr[left]);
left--;
}
while (right < n && res.size() < k) {
res.push_back(arr[right]);
right++;
}
return res;
}
int main() {
vector<int> arr =
{12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56};
int k = 4, x = 35;
vector<int> res = printKClosest(arr, k, x);
for (int val: res) cout << val << " ";
cout << endl;
return 0;
}
Java
// Java program to find k closest elements to a given value
class GfG {
// Function to find k closest elements to a given value
static int[] printKClosest(int[] arr, int k, int x) {
int n = arr.length;
int low = 0, high = n - 1, pos = -1;
// Binary search to find last element less than x
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] < x) {
pos = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
int left = pos, right = pos + 1;
// If value at right index is x, increment
if (right < n && arr[right] == x) right++;
int[] res = new int[k];
int count = 0;
// Use two-pointer technique to pick k closest elements
while (left >= 0 && right < n && count < k) {
int leftDiff = Math.abs(arr[left] - x);
int rightDiff = Math.abs(arr[right] - x);
if (leftDiff < rightDiff) {
res[count++] = arr[left];
left--;
}
else {
res[count++] = arr[right];
right++;
}
}
// If k elements are not filled
while (left >= 0 && count < k) {
res[count++] = arr[left];
left--;
}
while (right < n && count < k) {
res[count++] = arr[right];
right++;
}
return res;
}
public static void main(String[] args) {
int[] arr =
{12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56};
int k = 4, x = 35;
int[] res = printKClosest(arr, k, x);
for (int val : res) System.out.print(val + " ");
System.out.println();
}
}
Python
# Python program to find k closest elements to a given value
# Function to find k closest elements to a given value
def printKClosest(arr, k, x):
n = len(arr)
low, high, pos = 0, n - 1, -1
# Binary search to find last element less than x
while low <= high:
mid = (low + high) // 2
if arr[mid] < x:
pos = mid
low = mid + 1
else:
high = mid - 1
left, right = pos, pos + 1
# If value at right index is x, increment
if right < n and arr[right] == x:
right += 1
res = []
# Use two-pointer technique to pick k closest elements
while left >= 0 and right < n and len(res) < k:
leftDiff = abs(arr[left] - x)
rightDiff = abs(arr[right] - x)
if leftDiff < rightDiff:
res.append(arr[left])
left -= 1
else:
res.append(arr[right])
right += 1
# If k elements are not filled
while left >= 0 and len(res) < k:
res.append(arr[left])
left -= 1
while right < n and len(res) < k:
res.append(arr[right])
right += 1
return res
if __name__ == "__main__":
arr = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56]
k = 4
x = 35
res = printKClosest(arr, k, x)
print(' '.join(map(str, res)))
C#
// C# program to find k closest elements to a given value
using System;
class GfG {
// Function to find k closest elements to a given value
static int[] printKClosest(int[] arr, int k, int x) {
int n = arr.Length;
int low = 0, high = n - 1, pos = -1;
// Binary search to find last element less than x
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] < x) {
pos = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
int left = pos, right = pos + 1;
// If value at right index is x, increment
if (right < n && arr[right] == x) right++;
int[] res = new int[k];
int count = 0;
// Use two-pointer technique to pick k closest elements
while (left >= 0 && right < n && count < k) {
int leftDiff = Math.Abs(arr[left] - x);
int rightDiff = Math.Abs(arr[right] - x);
if (leftDiff < rightDiff) {
res[count++] = arr[left];
left--;
}
else {
res[count++] = arr[right];
right++;
}
}
// If k elements are not filled
while (left >= 0 && count < k) {
res[count++] = arr[left];
left--;
}
while (right < n && count < k) {
res[count++] = arr[right];
right++;
}
return res;
}
static void Main() {
int[] arr =
{12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56};
int k = 4, x = 35;
int[] res = printKClosest(arr, k, x);
foreach (int val in res) Console.Write(val + " ");
Console.WriteLine();
}
}
JavaScript
// JavaScript program to find k closest elements to a given value
// Function to find k closest elements to a given value
function printKClosest(arr, k, x) {
let n = arr.length;
let low = 0, high = n - 1, pos = -1;
// Binary search to find last element less than x
while (low <= high) {
let mid = Math.floor((low + high) / 2);
if (arr[mid] < x) {
pos = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
let left = pos, right = pos + 1;
// If value at right index is x, increment
if (right < n && arr[right] === x) right++;
let res = [];
// Use two-pointer technique to pick k closest elements
while (left >= 0 && right < n && res.length < k) {
let leftDiff = Math.abs(arr[left] - x);
let rightDiff = Math.abs(arr[right] - x);
if (leftDiff < rightDiff) {
res.push(arr[left]);
left--;
}
else {
res.push(arr[right]);
right++;
}
}
// If k elements are not filled
while (left >= 0 && res.length < k) {
res.push(arr[left]);
left--;
}
while (right < n && res.length < k) {
res.push(arr[right]);
right++;
}
return res;
}
let arr = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56];
let k = 4, x = 35;
let res = printKClosest(arr, k, x);
console.log(res.join(' '));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem