K-th Smallest Prime Fraction

Among all i<j pairs from a sorted array, return the kth smallest fraction arr[i]/arr[j] via a min-heap.

Medium
Time O((n + k) log n) Space O(n)
LeetCode
5 min read
k-way-merge heaps

Problem#

Given a sorted ascending array arr of distinct primes (and 1), find the kth smallest fraction arr[i]/arr[j] with 0 <= i < j < n.

Examples#

  • arr = [1,2,3,5], k = 3[2,5] (fraction 2/5)

Constraints#

  • 2 <= n <= 1000.

Approach#

For each denominator j, the smallest fraction with that denominator is arr[0]/arr[j]. Push these n - 1 starting fractions into a min-heap; pop k times, advancing the numerator pointer after each pop.

Solution#

K-th Smallest Prime Fraction
class Solution {
public:
vector<int> kthSmallestPrimeFraction(vector<int>& arr, int k) {
int n = arr.size();
auto cmp = [&](const pair<int,int>& a, const pair<int,int>& b){
return (long long)arr[a.first] * arr[b.second] > (long long)arr[b.first] * arr[a.second];
};
priority_queue<pair<int,int>, vector<pair<int,int>>, decltype(cmp)> pq(cmp);
for (int j = 1; j < n; ++j) pq.push({0, j});
while (--k > 0) {
auto [i, j] = pq.top(); pq.pop();
if (i + 1 < j) pq.push({i + 1, j});
}
auto [i, j] = pq.top();
return {arr[i], arr[j]};
}
};

Editorial#

Comparing fractions via cross-multiplication keeps everything in integer arithmetic. Each denominator’s fractions form a monotone sequence (numerator grows ⇒ fraction grows), so the k-way merge applies: the heap holds one frontier per denominator.

Complexity#

  • Time: O((n + k) log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.