educative.io

Simpler solution for kth smallest number

Hi,

why not simply searching for the kth smallest number like this:

public static int findKthSmallestNumber(int[] nums, int k) {
  Queue<Integer> q = new PriorityQueue<Integer>((a, b) -> b - a);
  for (int i : nums) {
    q.offer(i);
    if (q.size() > k) {
      q.poll();
    }
  }

  return q.poll();
}

It is much simpler and uses O(k) space.

Thanks


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Kth Smallest Number (easy) - Grokking the Coding Interview: Patterns for Coding Questions

Hi @Timo_Guhring
Thanks for your suggestion, the given solution is just for the implementation purpose. Your solution is also correct so you can use it as well.
Your feedback is much appreciated :slight_smile: