Bird
Raised Fist0
DSA Javaprogramming

Kth Smallest Element Using Min Heap in DSA Java

Choose your learning style10 modes available
Mental Model
A min heap keeps the smallest element at the top, so by removing the smallest element k times, we get the kth smallest.
Analogy: Imagine a line of kids holding balloons with numbers. The kid with the smallest number is always at the front. If you ask the first kid to step out k times, the last one who steps out holds the kth smallest number.
Min Heap Array Representation:
       [3]
      /   \
    [5]   [8]
   /  \
 [10] [12]

Array form: [3, 5, 8, 10, 12]
Top is smallest element 3
Dry Run Walkthrough
Input: array: [7, 10, 4, 3, 20, 15], k=3
Goal: Find the 3rd smallest element in the array using a min heap
Step 1: Build min heap from array
[3, 7, 4, 10, 20, 15]
Why: Heapify arranges elements so smallest is at the root
Step 2: Extract min (1st smallest): remove 3
[4, 7, 15, 10, 20]
Why: Remove smallest element to move towards kth smallest
Step 3: Extract min (2nd smallest): remove 4
[7, 10, 15, 20]
Why: Remove next smallest element
Step 4: Extract min (3rd smallest): remove 7
[10, 20, 15]
Why: The removed element 7 is the 3rd smallest
Result:
[10, 20, 15]
3rd smallest element is 7
Annotated Code
DSA Java
import java.util.PriorityQueue;

public class KthSmallestMinHeap {

    public static int kthSmallest(int[] arr, int k) {
        if (arr == null || arr.length == 0 || k < 1 || k > arr.length) {
            return -1;
        }
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        // Add all elements to min heap
        for (int num : arr) {
            minHeap.add(num); // add element to heap
        }
        int result = -1;
        // Extract min k times
        for (int i = 0; i < k; i++) {
            result = minHeap.poll(); // remove smallest element
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {7, 10, 4, 3, 20, 15};
        int k = 3;
        int kthSmallest = kthSmallest(arr, k);
        String suffix = (k == 1) ? "st" : (k == 2) ? "nd" : (k == 3) ? "rd" : "th";
        System.out.println(k + suffix + " smallest element is " + kthSmallest);
    }
}
minHeap.add(num);
Add each element to the min heap to build the heap
result = minHeap.poll();
Remove the smallest element from the heap k times
OutputSuccess
3rd smallest element is 7
Complexity Analysis
Time: O(n log n + k log n) because building the heap takes O(n log n) and each of the k extractions takes O(log n)
Space: O(n) because the heap stores all n elements
vs Alternative: Using sorting takes O(n log n), which is asymptotically similar to this heap approach.
Edge Cases
k is larger than array length
Returns -1 since kth element does not exist
DSA Java
return -1;
array is empty
Returns -1 as no elements to extract
DSA Java
return -1;
k is 1 (smallest element)
Returns the minimum element correctly
DSA Java
result = minHeap.poll();
When to Use This Pattern
When you need the kth smallest or largest element efficiently, use a heap to avoid full sorting.
Common Mistakes
Mistake: Extracting elements from the heap less or more than k times
Fix: Ensure exactly k extractions to get the kth smallest
Mistake: Using max heap instead of min heap for kth smallest
Fix: Use min heap for kth smallest; max heap is for kth largest
Summary
Finds the kth smallest element by removing the smallest element k times from a min heap.
Use when you want kth smallest without sorting the entire array.
The smallest element is always at the top of the min heap, so repeated removal leads to kth smallest.

Practice

(1/5)
1. What does the kth smallest element mean in a list of numbers?
easy
A. The element that is the kth in ascending order
B. The largest element in the list
C. The element that appears kth from the end
D. The element with the kth highest frequency

Solution

  1. Step 1: Understand the meaning of kth smallest

    The kth smallest element is the element that would appear at position k if the list was sorted in ascending order.
  2. Step 2: Compare with other options

    Options B, C, and D describe different concepts: largest element, kth from end, and frequency-based element, which are not the kth smallest.
  3. Final Answer:

    The element that is the kth in ascending order -> Option A
  4. Quick Check:

    kth smallest = kth element in sorted list [OK]
Hint: Sort the list; kth smallest is element at index k-1 [OK]
Common Mistakes:
  • Confusing kth smallest with kth largest
  • Thinking kth smallest means kth from the end
  • Mixing element frequency with position
2. Which Java code snippet correctly creates a min heap using PriorityQueue to find the kth smallest element?
easy
A. PriorityQueue<Integer> minHeap = new PriorityQueue<>(Comparator.reverseOrder());
B. PriorityQueue<Integer> minHeap = new PriorityQueue<>(Collections.reverseOrder());
C. PriorityQueue<Integer> minHeap = new PriorityQueue<>(Collections.reverseOrder(), k);
D. PriorityQueue<Integer> minHeap = new PriorityQueue<>();

Solution

  1. Step 1: Identify min heap creation syntax

    In Java, new PriorityQueue<>() creates a min heap by default.
  2. Step 2: Analyze other options

    Options B, C, and D create max heaps using reverse order comparators.
  3. Final Answer:

    PriorityQueue<Integer> minHeap = new PriorityQueue<>(); -> Option D
  4. Quick Check:

    Default PriorityQueue = min heap [OK]
Hint: Use PriorityQueue without comparator for min heap [OK]
Common Mistakes:
  • Using reverseOrder() creates max heap, not min heap
  • Confusing initial capacity with heap type
  • Not importing java.util.PriorityQueue
3. What is the output of the following Java code snippet?
int[] arr = {7, 10, 4, 3, 20, 15};
int k = 3;
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : arr) {
    minHeap.add(num);
}
int result = 0;
for (int i = 0; i < k; i++) {
    result = minHeap.poll();
}
System.out.println(result);
medium
A. 10
B. 4
C. 7
D. 3

Solution

  1. Step 1: Add all elements to min heap

    Elements added: 7, 10, 4, 3, 20, 15. Min heap orders them internally as 3,4,7,10,15,20.
  2. Step 2: Poll k=3 times from min heap

    First poll: 3, second poll: 4, third poll: 7. The variable result holds the last polled value, 7.
  3. Final Answer:

    7 -> Option C
  4. Quick Check:

    3rd smallest element = 7 [OK]
Hint: Poll k times from min heap; last polled is kth smallest [OK]
Common Mistakes:
  • Returning first polled element instead of kth
  • Confusing min heap order with insertion order
  • Off-by-one error in loop count
4. Identify the error in this Java code to find kth smallest element using min heap:
int kthSmallest(int[] arr, int k) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    for (int i = 0; i <= arr.length; i++) {
        minHeap.add(arr[i]);
    }
    int result = 0;
    for (int i = 0; i < k; i++) {
        result = minHeap.poll();
    }
    return result;
}
medium
A. Loop condition should be i < arr.length, not i <= arr.length
B. PriorityQueue should be max heap, not min heap
C. Poll loop should run k+1 times
D. Return statement should return minHeap.peek()

Solution

  1. Step 1: Check array loop bounds

    The for loop uses i <= arr.length, which causes ArrayIndexOutOfBoundsException because valid indices are 0 to arr.length-1.
  2. Step 2: Verify other parts

    Min heap is correct for kth smallest. Poll loop runs k times correctly. Return statement returns last polled element, which is correct.
  3. Final Answer:

    Loop condition should be i < arr.length, not i <= arr.length -> Option A
  4. Quick Check:

    Array index out of bounds due to loop condition [OK]
Hint: Use i < arr.length to avoid index errors [OK]
Common Mistakes:
  • Using <= instead of < in array loops
  • Changing heap type unnecessarily
  • Polling wrong number of times
5. Given a large array with millions of elements, which approach is most efficient to find the kth smallest element?
hard
A. Add all elements to a min heap and poll k times
B. Add first k elements to a max heap, then for each remaining element, replace root if smaller
C. Sort the entire array and pick element at index k-1
D. Use a hash map to count frequencies and pick kth smallest key

Solution

  1. Step 1: Understand efficiency of adding all elements to min heap

    Adding all millions of elements to a min heap and polling k times is O(n + k log n), which is costly for large n.
  2. Step 2: Use max heap of size k for better efficiency

    Adding first k elements to a max heap keeps track of k smallest seen so far. For each new element, if smaller than max heap root, replace root. This is O(n log k), much better for large n.
  3. Step 3: Compare other options

    Sorting entire array is O(n log n), slower than max heap approach. Hash map frequency counting is not suitable for kth smallest element.
  4. Final Answer:

    Add first k elements to a max heap, then for each remaining element, replace root if smaller -> Option B
  5. Quick Check:

    Max heap of size k = efficient kth smallest [OK]
Hint: Use max heap of size k for large arrays [OK]
Common Mistakes:
  • Using min heap with all elements for large data
  • Sorting entire array unnecessarily
  • Confusing frequency counting with order statistics
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard