1
+
1
2
package com .thealgorithms .datastructures .heaps ;
2
3
3
4
import java .util .PriorityQueue ;
4
5
6
+ /**
7
+ * This class provides methods to find the Kth largest or Kth smallest element
8
+ * in an array using heaps. It leverages a min-heap to find the Kth largest element
9
+ * and a max-heap to find the Kth smallest element efficiently.
10
+ *
11
+ * @author Hardvan
12
+ */
5
13
public class KthElementFinder {
14
+
15
+ /**
16
+ * Finds the Kth largest element in the given array.
17
+ * Uses a min-heap of size K to track the largest K elements.
18
+ *
19
+ * Time Complexity: O(n * log(k)), where n is the size of the input array.
20
+ * Space Complexity: O(k), as we maintain a heap of size K.
21
+ *
22
+ * @param nums the input array of integers
23
+ * @param k the desired Kth position (1-indexed, i.e., 1 means the largest element)
24
+ * @return the Kth largest element in the array
25
+ */
6
26
public static int findKthLargest (int [] nums , int k ) {
7
27
PriorityQueue <Integer > minHeap = new PriorityQueue <>(k );
8
28
for (int num : nums ) {
@@ -14,6 +34,17 @@ public static int findKthLargest(int[] nums, int k) {
14
34
return minHeap .peek ();
15
35
}
16
36
37
+ /**
38
+ * Finds the Kth smallest element in the given array.
39
+ * Uses a max-heap of size K to track the smallest K elements.
40
+ *
41
+ * Time Complexity: O(n * log(k)), where n is the size of the input array.
42
+ * Space Complexity: O(k), as we maintain a heap of size K.
43
+ *
44
+ * @param nums the input array of integers
45
+ * @param k the desired Kth position (1-indexed, i.e., 1 means the smallest element)
46
+ * @return the Kth smallest element in the array
47
+ */
17
48
public static int findKthSmallest (int [] nums , int k ) {
18
49
PriorityQueue <Integer > maxHeap = new PriorityQueue <>((a , b ) -> b - a );
19
50
for (int num : nums ) {
0 commit comments