Given a sorted array arr[] of unique integers, an integer k, and a target value x. Return exactly k elements from the array closest to x, excluding x if it exists.
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)
Return the k closest elements in order of closeness.
Examples:
Input: arr[] = [1, 3, 4, 10, 12], k = 2, x = 4
Output: [3, 1]
Explanation: The value 4 is excluded from consideration.
The closest element to 4 is 3 with a distance of 1.
The next closest element is 1 with a distance of 3.Input: arr[] = [10, 20, 30, 40, 50], k = 3, x = 25
Output: [30, 20, 40]
Explanation: First closest element to 25 is 30, Since 30 > 20.
Second closest element to 25 is 20.
Third closest element to 25 is 40.
Table of Content
[Naive Approach] 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 custom sorted array then return it.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
vector<int> findKClosest(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;
}
int main() {
vector<int> arr = {1, 3, 4, 10, 12};
int k = 2;
int x = 4;
vector<int> closest = findKClosest(arr, k, x);
for (int num : closest) {
cout << num << " ";
}
return 0;
}
import java.util.ArrayList;
import java.util.List;
public class GFG {
public static ArrayList<Integer> findKClosest(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;
});
ArrayList<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;
}
return result;
}
// Main function with example
public static void main(String[] args) {
int[] arr = {1, 3, 4, 10, 12};
int k = 2;
int x = 4;
ArrayList<Integer> closest = findKClosest(arr, k, x);
for (int num : closest) {
System.out.print(num + " ");
}
}
}
def findKClosest(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 = [1, 3, 4, 10, 12]
k = 2
x = 4
closest = findKClosest(arr, k, x)
print( *closest)
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
public static List<int> findKClosest(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;
}
static void Main(){
int[] arr = { 1, 3, 4, 10, 12 };
int k = 2;
int x = 4;
List<int> closest = findKClosest(arr, k, x);
foreach (int num in closest){
Console.Write(num + " ");
}
}
}
function findKClosest(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);
// prefer larger element
if (diffA === diffB) return b - a;
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;
}
// Driver Code
let arr = [1, 3, 4, 10, 12];
let k = 2;
let x = 4;
let closest = findKClosest(arr, k, x);
console.log(...closest);
Output
3 1
[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.
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<int> findKClosest(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 (right < n && 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 = {1, 3, 4, 10, 12};
int k = 2, x = 4;
vector<int> res = findKClosest(arr, k, x);
for (int val : res)
cout << val << " ";
cout << endl;
return 0;
}
import java.util.ArrayList;
class GFG {
// Function to find k closest elements to a given value
static ArrayList<Integer> findKClosest(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;
int right = i;
// If value at right index is x, increment
if (right < n && arr[right] == x)
right++;
ArrayList<Integer> res = new ArrayList<>();
while (left >= 0 && right < n && res.size() < k) {
int leftDiff = Math.abs(arr[left] - x);
int rightDiff = Math.abs(arr[right] - x);
if (leftDiff < rightDiff) {
res.add(arr[left]);
left--;
}
else {
res.add(arr[right]);
right++;
}
}
// If k elements are not filled
while (left >= 0 && res.size() < k) {
res.add(arr[left]);
left--;
}
while (right < n && res.size() < k) {
res.add(arr[right]);
right++;
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 3, 4, 10, 12};
int k = 2, x = 4;
ArrayList<Integer> res = findKClosest(arr, k, x);
for (int val : res)
System.out.print(val + " ");
System.out.println();
}
}
def findKClosest(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 = [1, 3, 4, 10, 12]
k = 2
x = 4
res = findKClosest(arr, k, x)
print(' '.join(map(str, res)))
using System;
using System.Collections.Generic;
class GFG {
static List<int> findKClosest(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++;
List<int> res = new List<int>();
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.Add(arr[left]);
left--;
}
else {
res.Add(arr[right]);
right++;
}
count++;
}
// If k elements are not filled
while (left >= 0 && count < k) {
res.Add(arr[left]);
left--;
count++;
}
while (right < n && count < k) {
res.Add(arr[right]);
right++;
count++;
}
return res;
}
static void Main() {
int[] arr = {1, 3, 4, 10, 12};
int k = 2, x = 4;
List<int> res = findKClosest(arr, k, x);
foreach (int val in res) Console.Write(val + " ");
Console.WriteLine();
}
}
function findKClosest(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;
}
// Driver code
let arr = [1, 3, 4, 10, 12];
let k = 2, x = 4;
let res = findKClosest(arr, k, x);
console.log(res.join(' '));
Output
3 1
[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.
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<int> findKClosest(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 =
{1, 3, 4, 10, 12};
int k = 2, x = 4;
vector<int> res = findKClosest(arr, k, x);
for (int val: res) cout << val << " ";
cout << endl;
return 0;
}
import java.util.ArrayList;
class GFG {
static ArrayList<Integer> findKClosest(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++;
ArrayList<Integer> res = new ArrayList<>();
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.add(arr[left]);
left--;
} else {
res.add(arr[right]);
right++;
}
count++;
}
// If k elements are not filled
while (left >= 0 && count < k) {
res.add(arr[left]);
left--;
count++;
}
while (right < n && count < k) {
res.add(arr[right]);
right++;
count++;
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 3, 4, 10, 12};
int k = 2, x = 4;
ArrayList<Integer> res = findKClosest(arr, k, x);
for (int val : res) System.out.print(val + " ");
System.out.println();
}
}
def findKClosest(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 = [1, 3, 4, 10, 12]
k = 2
x = 4
res = findKClosest(arr, k, x)
print(' '.join(map(str, res)))
using System;
using System.Collections.Generic;
class GFG {
static List<int> findKClosest(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++;
List<int> res = new List<int>();
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.Add(arr[left]);
count++;
left--;
}
else {
res.Add(arr[right]);
count++;
right++;
}
}
// If k elements are not filled
while (left >= 0 && count < k) {
res.Add(arr[left]);
count++;
left--;
}
while (right < n && count < k) {
res.Add(arr[right]);
count++;
right++;
}
return res;
}
static void Main() {
int[] arr =
{1, 3, 4, 10, 12};
int k = 2, x = 4;
List<int> res = findKClosest(arr, k, x);
foreach (int val in res) Console.Write(val + " ");
Console.WriteLine();
}
}
function findKClosest(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;
}
// Driver code
let arr = [1, 3, 4, 10, 12];
let k = 2, x = 4;
let res = findKClosest(arr, k, x);
console.log(res.join(' '));
Output
3 1