Open In App

Closest K Elements in a Sorted Array

Last Updated : 11 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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);

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.

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(' '));

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.

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(' '));

Output
39 30 42 45 

Next Article

Similar Reads