# Find K Closest Elements LeetCode Solution

Here, We see Find K Closest Elements LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

# List of all LeetCode Solution

## Problem Statement

Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

An integer a is closer to x than an integer b if:

• |a – x| < |b – x|, or
• |a – x| == |b – x| and a < b

Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]

Example 2:
Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]

## Find K Closest Elements LeetCode Solution C++

``````class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
for (int i = 0; i < arr.size(); i++)
pq.push({abs(arr[i] - x), arr[i]});
vector<int> ans;
for (int i = 0; i < k; i++)
{
ans.push_back(pq.top().second);
pq.pop();
}
sort(ans.begin(), ans.end());
return ans;
}
};```Code language: PHP (php)```

## Find K Closest Elements Solution Java

``````class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
int start = 0;
int end = arr.length - 1;
while (end - start >= k) {
if (Math.abs(arr[start] - x) > Math.abs(arr[end] - x)) {
start++;
} else {
end--;
}
}
List<Integer> result = new ArrayList<>(k);
for (int i = start; i <= end; i++) {
}
return result;
}
}```Code language: PHP (php)```

## Find K Closest Elements Solution JavaScript

``````var findClosestElements = function (arr, k, x) {
let leftPointer = 0;
let rightPointer = arr.length - 1;
while (rightPointer - leftPointer >= k) {
if (Math.abs(arr[leftPointer] - x) <= Math.abs(arr[rightPointer] - x)) rightPointer--;
else leftPointer++;
}
return arr.slice(leftPointer, rightPointer + 1);
};```Code language: JavaScript (javascript)```

## Find K Closest Elements Solution Python

``````class Solution(object):
def findClosestElements(self, arr, k, x):
lo, hi = 0, len(arr)-k
while lo<hi:
mid = (lo + hi)//2
if x-arr[mid]>arr[mid+k]-x:
lo = mid + 1
else:
hi = mid
return arr[lo:lo+k]```Code language: HTML, XML (xml)```
Scroll to Top