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

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

Help your peers!
Add answer anonymously...
Trilogy Innovations Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter