Given a sorted array of integers arr
containing 1
and prime numbers, you need to find the k
-th smallest fraction in the form arr[i]/arr[j]
where 0 <= i < j < arr.length
. Return the fraction in the form of an array of two integers [arr[i], arr[j]]
.
arr
: What are the possible values or size ranges for arr
?
k
: Is k
always valid, i.e., does k
always fall within the range of possible fractions?
k
will always be valid as per the constraints.arr
contain duplicate numbers?
arr
contains only 1
and distinct prime numbers.[arr[i], arr[j]]
.arr[0]/arr[arr.length-1]
) and the largest fraction (arr[arr.length-2]/arr[arr.length-1]
).low
) and Right (high
): Initialize the search range for fractions.low
and high
based on the count.import java.util.PriorityQueue;
class Solution {
public int[] kthSmallestPrimeFraction(int[] arr, int k) {
double low = 0.0, high = 1.0;
while (low < high) {
double mid = (low + high) / 2.0;
int[] result = countFractions(arr, mid);
if (result[2] < k) {
low = mid;
} else {
high = mid;
}
if (Math.abs(low - high) < 1e-9) {
return new int[] {arr[result[0]], arr[result[1]]};
}
}
return new int[] {}; // Should never be reached.
}
private int[] countFractions(int[] arr, double mid) {
int count = 0;
int n = arr.length;
int x = 0, y = n - 1;
int best_i = 0, best_j = 0;
double best_fraction = 0.0;
for (int i = 0; i < n; i++) {
while (y >= 0 && (double) arr[i] / arr[y] > mid) {
y--;
}
if (y >= 0) {
count += y + 1;
if ((double) arr[i] / arr[y] > best_fraction) {
best_i = i;
best_j = y;
best_fraction = (double) arr[i] / arr[y];
}
}
}
return new int[] {best_i, best_j, count};
}
}
O(log(1/epsilon))
, where epsilon
is the precision level.O(n)
.O(n log(1/epsilon))
, where n
is the size of the input array. Given practical limits, this is efficient.This solution efficiently finds the k-th smallest prime fraction using a combination of binary search and counting methodology.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?