Open In App

Closest K Elements in a Sorted Array

Last Updated : 29 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sorted array arr[] of unique elements and a value x, find the k closest elements to x in arr[]. 

Note that if the element is present in array, then it should not be in output, only the other closest elements are required.

Examples: 

Input: k = 4, x = 35, arr[] = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56]
Output: 39 30 42 45

Input: k = 2, x = 4, arr[] = {1, 3, 4, 10, 12}
Output: 3 1

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

The idea is to linearly find the last element which is less than or equal to the given target value, then use two pointers to pick k closest elements by comparing differences and ensuring the target value is skipped if present.

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 use binary search to quickly find the last element in the array that is less than or equal to the target value, and then apply a two-pointer method to pick the k closest elements while respecting 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;
    
    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;
        
        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 = []
    
    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;
        
        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 = [];
    
    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