Find K Closest Elements

You are given a sorted array 'A' of length 'N', two integers 'K' and 'X'. Your task is to print 'K' integers closest to 'X', if two integers are at the same distance return the smaller one.

The output should also be in sorted order

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 )
For Example:
if X = 4,  3 is closer to 'X' than 9, as |3-4| < |9-4|  i.e., 1 < 5   and if X = 4, 2 and 6 are equally close to it, as |2-4| == |6-4| = 2, but we say 2 is closer to 4 than 6, as 2 is smaller.
Input Format:
The first line of the input contains ‘T’ denoting the number of test cases.

The first line of each test case contains the three integers 'N', 'K', and 'X'.

The second line of each test case contains 'N' space-separated integers of the array 'A'. 
Output Format:
Return the k space-separated integers.

The output of each test case is printed on a new line.
Constraints:
1 <= T <= 5
1 <= N, K <= 5000
1 <= A[i], X <=10^6

Time Limit: 1 second
CodingNinjas
author
2y

I proposed the following solution -
Perform a binary search on distance. In each iteration of the binary search, check how many pairs have a distance less than mid and then update low and high bounds ...read more

CodingNinjas
author
2y
Sort After Taking the Difference

Explanation:

  • The key idea is to sort the array using comparator where elements are compared based on the condition: |a - X| < |b - X| or ( |a - X| == |b - X| and a < b ...read more
CodingNinjas
author
2y
Binary Search

The key idea is that we know that the final answer will be some contiguous sequence in array ‘A’. So we initially take the complete array as our answer then reduce its range.

Algorithm:

  • I...read more
Aritra Ray
1y

Hope this C++ code will help you :)

#define pair pair 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 closestelements(vector &a , int k , int x){

int left=0;

int right=a.size()-1;

while(left

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

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

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

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
Get AmbitionBox app

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