Educative

Alternative Solution [Java]

public static List<Integer> findClosestElements(int[] arr, int K, Integer X) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a,b) -> Math.abs(b - X) - Math.abs(a - X));
    
    for(int num : arr){
      maxHeap.offer(num);
      if(maxHeap.size() > K){
        maxHeap.poll();
      }    
    }

    ArrayList<Integer> results = new ArrayList<>(maxHeap);
    Collections.sort(results);
    
    return results;
  }

Time complexity for this would N * Log K.

Hi @Gaurav7, could you explain why this is O(N * Log K) so I can better understand please?