Skip to content

Commit d80b123

Browse files
committed
Fix
1 parent 5ef4c96 commit d80b123

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,28 @@
1+
12
package com.thealgorithms.datastructures.heaps;
23

34
import java.util.PriorityQueue;
45

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+
*/
513
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+
*/
626
public static int findKthLargest(int[] nums, int k) {
727
PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
828
for (int num : nums) {
@@ -14,6 +34,17 @@ public static int findKthLargest(int[] nums, int k) {
1434
return minHeap.peek();
1535
}
1636

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+
*/
1748
public static int findKthSmallest(int[] nums, int k) {
1849
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
1950
for (int num : nums) {

0 commit comments

Comments
 (0)