The problem involves finding the K-th
smallest fraction formed by two elements from a sorted array of prime numbers. Each fraction is of the form A[i] / A[j]
where i < j
.
This problem can be efficiently solved using a min-heap to track the smallest fractions.
class Solution {
public int[] kthSmallestPrimeFraction(int[] arr, int k) {
PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) ->
arr[a[0]] * arr[b[1]] - arr[b[0]] * arr[a[1]]);
// Step 1: Add the first fraction from each element in arr with the last element
for (int i = 0; i < arr.length - 1; i++) {
minHeap.offer(new int[]{i, arr.length - 1}); // [numeratorIndex, denominatorIndex]
}
// Step 2: Extract the smallest fractions from the heap
while (--k > 0) {
int[] smallest = minHeap.poll();
int i = smallest[0];
int j = smallest[1];
// Add the next fraction with the same numerator but a smaller denominator
if (j - 1 > i) {
minHeap.offer(new int[]{i, j - 1});
}
}
int[] result = minHeap.poll();
return new int[]{arr[result[0]], arr[result[1]]};
}
}
O(n log n)
โ Adding the first fractions to the heap.O(k log n)
โ Extracting and adding elements to the heap for k
fractions.O(k log n)
.Input: arr = [1, 2, 3, 5], k = 3
Output: [2, 5]
Explanation:
- The fractions are [1/5, 1/3, 1/2, 2/5, 3/5].
- The 3rd smallest fraction is 2/5.
k
greater than the total number of fractions.