Open in App
Not now

# Find K closest elements to given Value in Unsorted Array

• Difficulty Level : Medium
• Last Updated : 31 Aug, 2022

Given an unsorted array arr[] and two numbers X and K, the task is to find K closest values to X in arr[].

Examples:

Input: arr[] = {10, 2, 14, 4, 7, 6}, X = 5, K = 3
Output: 4 6 7
Explanation: Three closest values of x are 4, 6 and 7.

Input: arr[] = {-10, -50, 20, 17, 80}, X = 20, K = 2
Output: 17 20

Recommended Practice

### Find K closest Element by Sorting the Array:

The simple idea is to sort the array. Then apply the method discussed to K closest values in a sorted array.

### Find K closest Element using Heap:

An efficient approach is to use a max heap data structure of size K

Find the absolute difference of the array elements with X and push them in the heap. If at any position the heap gets filled then only push elements when it has an absolute difference less than the first element of the max heap.

Follow the steps mentioned below to implement the idea:

• Build a max heap of size K.
• Initially push the first K elements of the array with their absolute difference from X.
• Now traverse from K+1 to N:
• If the absolute difference is less than the maximum difference stored in the heap, then remove the maximum difference and insert the current difference.
• After the traversal is over, the K elements stored in the heap are the required K closest elements.

Below is the implementation of the above approach.

## C++

 `// C++ program to find k closest elements`   `#include ` `using` `namespace` `std;`   `// Function to find the K closest elements` `void` `printKclosest(``int` `arr[], ``int` `n, ``int` `x,` `                   ``int` `k)` `{` `    ``// Make a max heap of difference with` `    ``// first k elements.` `    ``priority_queue > pq;` `    ``for` `(``int` `i = 0; i < k; i++)` `        ``pq.push({ ``abs``(arr[i] - x), i });`   `    ``// Now process remaining elements.` `    ``for` `(``int` `i = k; i < n; i++) {`   `        ``int` `diff = ``abs``(arr[i] - x);`   `        ``// If difference with current` `        ``// element is more than root,` `        ``// then ignore it.` `        ``if` `(diff > pq.top().first)` `            ``continue``;`   `        ``// Else remove root and insert` `        ``pq.pop();` `        ``pq.push({ diff, i });` `    ``}`   `    ``// Print contents of heap.` `    ``while` `(pq.empty() == ``false``) {` `        ``cout << arr[pq.top().second] << ``" "``;` `        ``pq.pop();` `    ``}` `}`   `// Driver code` `int` `main()` `{` `    ``int` `arr[] = { -10, -50, 20, 17, 80 };` `    ``int` `X = 20, K = 2;` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    `  `    ``// Function call` `    ``printKclosest(arr, N, X, K);` `    ``return` `0;` `}`

## Java

 `// Java program to find k closest elements`   `import` `java.util.Comparator;` `import` `java.util.PriorityQueue;`   `class` `Pair {` `    ``Integer key;` `    ``Integer value;`   `    ``public` `Pair(Integer key, Integer value)` `    ``{` `        ``this``.key = key;` `        ``this``.value = value;` `    ``}` `    ``public` `Integer getKey() { ` `        ``return` `key; ` `    ``}` `    ``public` `void` `setKey(Integer key) { ` `        ``this``.key = key; ` `    ``}` `    ``public` `Integer getValue() { ` `        ``return` `value; ` `    ``}` `    ``public` `void` `setValue(Integer value)` `    ``{` `        ``this``.value = value;` `    ``}` `}`   `class` `GFG {`   `    ``public` `static` `void` `printKclosest(``int``[] arr, ``int` `n,` `                                     ``int` `x, ``int` `k)` `    ``{` `        ``// Make a max heap.` `        ``PriorityQueue pq` `            ``= ``new` `PriorityQueue<>(``new` `Comparator() {` `                  ``public` `int` `compare(Pair p1, Pair p2)` `                  ``{` `                      ``return` `p2.getValue().compareTo(` `                          ``p1.getValue());` `                  ``}` `              ``});`   `        ``// Build heap of difference with` `        ``// first k elements` `        ``for` `(``int` `i = ``0``; i < k; i++) {` `            ``pq.offer(` `                ``new` `Pair(arr[i], Math.abs(arr[i] - x)));` `        ``}`   `        ``// Now process remaining elements.` `        ``for` `(``int` `i = k; i < n; i++) {` `            ``int` `diff = Math.abs(arr[i] - x);`   `            ``// If difference with current` `            ``// element is more than root,` `            ``// then ignore it.` `            ``if` `(diff > pq.peek().getValue())` `                ``continue``;`   `            ``// Else remove root and insert` `            ``pq.poll();` `            ``pq.offer(``new` `Pair(arr[i], diff));` `        ``}`   `        ``// Print contents of heap.` `        ``while` `(!pq.isEmpty()) {` `            ``System.out.print(pq.poll().getKey() + ``" "``);` `        ``}` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `arr[] = { -``10``, -``50``, ``20``, ``17``, ``80` `};` `        ``int` `X = ``20``, K = ``2``;` `        ``int` `N = arr.length;`   `        ``printKclosest(arr, N, X, K);` `    ``}` `}`   `// This code is contributed by Ashok Borra`

## Python3

 `# Python3 program to find k closest elements `   `import` `math` `import` `sys` `from` `queue ``import` `PriorityQueue`   `# Function to find the K closest elements` `def` `printKclosest(arr,n,x,k):`   `    ``# Make a max heap of difference with ` `    ``# first k elements. ` `    ``pq ``=` `PriorityQueue()` `    ``for` `i ``in` `range``(k):` `        ``pq.put((``-``abs``(arr[i]``-``x),i))`   `    ``# Now process remaining elements` `    ``for` `i ``in` `range``(k,n):` `        ``diff ``=` `abs``(arr[i]``-``x)` `        ``p,pi ``=` `pq.get()` `        ``curr ``=` `-``p`   `        ``# If difference with current ` `        ``# element is more than root, ` `        ``# then put it back. ` `        ``if` `diff>curr:` `            ``pq.put((``-``curr,pi))` `            ``continue` `        ``else``:`   `            ``# Else remove root and insert` `            ``pq.put((``-``diff,i))` `            `  `    ``# Print contents of heap.` `    ``while``(``not` `pq.empty()):` `        ``p,q ``=` `pq.get()` `        ``print``(``"{} "``.``format``(arr[q]),end ``=` `"")`   `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `    ``arr ``=` `[``-``10``,``-``50``,``20``,``17``,``80``]` `    ``X, K ``=` `20``,``2` `    ``N ``=` `len``(arr)` `    ``printKclosest(arr, N, X, K)`

## C#

 `// C# program to find k closest elements`   `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG {`   `    ``// Function to find the K closest elements` `    ``static` `void` `printKclosest(``int``[] arr, ``int` `n, ``int` `x,` `                              ``int` `k)` `    ``{` `        ``// Make a max heap of difference with` `        ``// first k elements.` `        ``List > pq` `            ``= ``new` `List >();` `        ``for` `(``int` `i = 0; i < k; i++) {` `            ``pq.Add(``new` `Tuple<``int``, ``int``>(Math.Abs(arr[i] - x),` `                                       ``i));` `        ``}`   `        ``pq.Sort();` `        ``pq.Reverse();`   `        ``// Now process remaining elements.` `        ``for` `(``int` `i = k; i < n; i++) {`   `            ``int` `diff = Math.Abs(arr[i] - x);`   `            ``// If difference with current` `            ``// element is more than root,` `            ``// then ignore it.` `            ``if` `(diff > pq[0].Item1)` `                ``continue``;`   `            ``// Else remove root and insert` `            ``pq.RemoveAt(0);` `            ``pq.Add(``new` `Tuple<``int``, ``int``>(diff, i));` `            ``pq.Sort();` `            ``pq.Reverse();` `        ``}`   `        ``// Print contents of heap.` `        ``while` `(pq.Count > 0) {` `            ``Console.Write(arr[pq[0].Item2] + ``" "``);` `            ``pq.RemoveAt(0);` `        ``}` `    ``}`   `    ``// Driver code` `    ``static` `void` `Main()` `    ``{` `        ``int``[] arr = { -10, -50, 20, 17, 80 };` `        ``int` `X = 20, K = 2;` `        ``int` `N = arr.Length;` `        ``printKclosest(arr, N, X, K);` `    ``}` `}`   `// This code is contributed by divyesh072019.`

Output

`17 20 `

Time Complexity: O(N * logK)
Auxiliary Space: O(K)

My Personal Notes arrow_drop_up
Related Articles