Find K Closest Elements

Given a sorted array 'A' of length 'N', and two integers 'K' and 'X', your task is to find 'K' integers from the array closest to 'X'. If two integers are at the same distance, prefer the smaller one.

Input:

T 
N K X
A[0] A[1] ... A[N-1]

Output:

B[0] B[1] ... B[K-1]

Example:

Input:
1 
8 3 5
1 2 3 4 5 6 7 8
Output:
4 5 6

Constraints:

  • 1 <= T <= 5
  • 1 <= N, K <= 5000
  • 1 <= A[i], X <= 10^6
Note:

An integer 'a' is closer to 'X' than an integer 'b' if: |a - X| < |b - X| or (|a - X| == |b - X| and a < b).

AnswerBot
4mo

Find K closest elements to X in a sorted array A.

  • Use binary search to find the closest element to X in the array.

  • Maintain two pointers to expand around the closest element to find K closest elements.

  • H...read more

Aritra Ray
1y

Hope this C++ code will help you :)

#define pair pair<int,int> class cmp{ public: bool operator()(pair a, pair b){ if(a.first!=b.first)return a.first>b.first; return a.second>b.second; } }; class Solut...read more

120 Thanuja
1y

vector<int> closestelements(vector<int> &a , int k , int x){

int left=0;

int right=a.size()-1;

while(left<right){

int mid = left + (right - left) / 2;

if (A[mid] == X) { left = mid; break;

} else if (A[mi...read more

Select
Add answer anonymously...
Trilogy Innovations Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits