Lucy's Neighbours | Practice | GeeksforGeeks

Lucy lives in house number X. She has a list of N house numbers in the society. Distance between houses can be determined by studying the difference between house numbers. Help her find out K closest neighbors.
Note: If two houses are equidistant and Lucy has to pick only one, the house with the smaller house number is given preference.
Example 1:
Input:
N = 5, X = 0, K = 4
a[] = {-21, 21, 4, -12, 20}, 
Output:
-21 -12 4 20
Explanation:
The closest neighbour is house
number 4. Followed by -12 and 20. -21 and 21 
are both equal distance from X=0. Therefore, 
Lucy can only pick 1. Based on the given 
condition she picks -21 as it is the smaller 
of the two. 

Example 2:
Input:
N = 6, X = 5, K = 3 
a[] = {10, 2, 14, 4, 7, 6},
Output:
4 6 7 

Your Task:  
You don't need to read input or print anything. Complete the function  Kclosest() which takes the array arr[], size of array N, X, and K as input parameters, and returns the list of numbers in sorted order.
Expected Time Complexity: O(NlogN)
Expected Auxiliary Space: O(N)
Constraints:
1 ≤ K ≤ N ≤ 105 
-104 ≤ X, arr[i] ≤ 104
0
artistdarkangel1 month ago
Java Solution | All test Case passed
Expected Time Complexity: O(NlogN)Expected Auxiliary Space: O(N)
 
 
class Solution { public ArrayList<Integer> Kclosest(int arr[], int n, int x, int k) {   ArrayList<Integer> arL = new ArrayList<Integer>();   PriorityQueue<Integer> pq = new PriorityQueue<Integer>();   HashSet<Integer> hs = new HashSet<Integer>();   Arrays.sort(arr);    for(int i=0; i<n; i++)   {      pq.add(Math.abs(arr[i]-x));      hs.add(arr[i]);   }   for(int i=0; i<k; i++)   {       Integer temp=pq.poll();       if(hs.contains(x-temp))       {           arL.add(x-temp);           hs.remove(x-temp);       }       else       {           int a=temp+x;           if(hs.contains(a))           {               arL.add(a);           }       }   }   Collections.sort(arL);   return arL;}}
0
shahabuddinbravo401 month ago
class Solution{   public:   vector<int> Kclosest(vector<int>arr, int n, int x, int k)    {        vector<pair<int,int>>vp;       for(int i=0;i<n;i++){           vp.push_back({abs(arr[i]-x),arr[i]});       }       sort(vp.begin(),vp.end());              vector<int>ans;       for(int i=0;i<k;i++){           ans.push_back(vp[i].second);       }       sort(ans.begin(),ans.end());       return ans;   }  };
+1
himanshukug19cs2 months ago
java soluuttion
 
class pair implements Comparable<pair>{   int hn;   int d;   pair(int hn,int d){       this.hn=hn;       this.d=d;   }public int compareTo(pair o){if(this.d==o.d)  return this.hn-o.hn;else  return this.d-o.d;}   }public ArrayList<Integer> Kclosest(int arr[], int n, int x, int k) {     // Your code goes here    ArrayList<Integer>  al = new ArrayList<Integer>();    PriorityQueue<pair> pq = new PriorityQueue<>();    for(int i=0;i<n;i++){        pair p = new pair(arr[i],Math.abs(x-arr[i]));        pq.add(p);    }    for(int i=0;i<k;i++){        al.add(pq.poll().hn);    }        Collections.sort(al);    return al;}} 
-1
darshitagupta3 months ago
vector<int> Kclosest(vector<int>arr, int n, int x, int k)    {        // Your code goes here        priority_queue<pair<int,int>>maxh;       vector<int>v;              for(int i=0;i<n;i++)       {           maxh.push({abs(arr[i]-x),arr[i]});           if(maxh.size()>k)           maxh.pop();       }              while(maxh.size()>0)       {           int temp=maxh.top().second;           v.push_back(temp);           maxh.pop();       }       sort(v.begin(),v.end());       return v;   }  
 
+1
abhixhek053 months ago
EASY TO UNDERSTAND C++ CODE, DONE USING MAX HEAP (PRIORITY QUEUE).
BASICALLY WE NEED TO FIND K CLOSEST ELEMENTS.
 
TC is O(Nlogk + klogk)
 
vector<int> Kclosest(vector<int>arr, int n, int x, int k) 
    { 
        // Your code goes here 
        priority_queue<pair<int,int>> q;
        for(int i=0;i<arr.size();i++){
            q.push({abs(arr[i]-x),arr[i],});
            if(q.size()>k) q.pop();
        }
        vector<int> ans;
        while(q.size()){
            
            ans.push_back(q.top().second);
            q.pop();
            
        }
        sort(ans.begin(),ans.end());
        return ans;
    }  
UPVOTE IF FOUND USEFULL 🍕🍕🍕
0
rishabh20183 months ago
0
raunakmishra12435 months ago
class Solution{
    public:
    vector<int> Kclosest(vector<int>arr, int n, int x, int k) 
    { 
        vector<int>v;
        priority_queue<pair<int,int>>maxh;
        for(int i=0;i<n;i++)
        {
            maxh.push({abs(x-arr[i]),arr[i]});
            if(maxh.size()>k)
            maxh.pop();
        }
        while(maxh.size()>0)
        {
            pair<int,int>p;
            p=maxh.top();
            v.push_back(p.second);
            maxh.pop();
        }
        sort(v.begin(),v.end());
        return v;
    }  
};
0
ssingh5be195 months ago
 vector<int> Kclosest(vector<int>arr, int n, int x, int k)    {        // Your code goes here        priority_queue<pair<int,int>> q;       for(int i=0;i<n;i++)       {           q.push(make_pair(abs(x-arr[i]),arr[i]));           if(q.size()>k)           q.pop();       }       // while(!q.empty())       // {       //     cout<<q.top().first<<"  "<<q.top().second<<endl;       //     q.pop();       // }       vector<int> v;       set<int> s;       while(!q.empty())       {           s.insert(q.top().second);           q.pop();       }       for(auto i:s)       {           v.push_back(i);       }       return v;   }  
0
Jay Kishan1 year ago
Jay Kishan
class Solution { public ArrayList<integer> Kclosest(int arr[], int n, int x, int k) {     int temp[] = new int[n];    Arrays.sort(arr);    for(int i=0;i<arr.length;i++){ temp[i]="Math.abs(arr[i]-x);" }="" arrays.sort(temp);="" int="" s="0;" arraylist<integer=""> list = new ArrayList<>();    while(s<k){ for(int="" i="0;i&lt;arr.length;i++){" if(temp[s]="=Math.abs(arr[i]-x)){" list.add(arr[i]);="" arr[i]="Integer.MAX_VALUE;" s++;="" i="arr.length;" }="" }="" }="" collections.sort(list);="" return="" list;="" }="" }="">
0
Well Fried
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.