K-th Smallest Prime Fraction (LeetCode 786): Solution and Explanation
Given a sorted array of 1 and distinct primes, look at every fraction arr[i] / arr[j] with i < j and return the kth smallest one as [numerator, denominator].
Intuition
Lay the fractions out in a grid: row i uses numerator arr[i], column j uses denominator arr[j], and only cells with j > i exist.
Along a row the numerator is fixed and the denominator grows to the right, so the fractions shrink to the right. Every row is a sorted list whose smallest entry sits over arr[n - 1].
Finding the kth smallest of several sorted lists is a k-way merge. Keep one candidate per row in a min-heap: the smallest fraction of that row not yet taken.
Each pop removes the next smallest fraction overall. The only new candidate is the next entry in the same row, one column to the left. After k - 1 pops the heap top is the answer.
Approach: K-way merge with a min-heap
- Push
(i, n - 1)for every rowi < n - 1, ordered byarr[i] / arr[n - 1]. - Repeat k - 1 times: pop the smallest
(i, j); ifj - 1 > i, push(i, j - 1). - Return
[arr[i], arr[j]]for the heap top. - Compare fractions by cross-multiplying,
arr[a.i] * arr[b.j] < arr[b.i] * arr[a.j], to avoid floating point.
Step-by-step example
arr = [1,2,3,5], k = 3
- Seed the heap with 1/5, 2/5 and 3/5.
- Pop 1/5 (first). Row 0 moves left: push 1/3.
- Pop 1/3 (second). Row 0 moves left: push 1/2.
- Two pops are done. The heap holds 2/5, 1/2 and 3/5, and its top 2/5 is the third smallest.
- Return [2,5].
Code: Python, Java, C++
1class Solution:
2 def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:
3 n = len(arr)
4 heap = [(arr[i] / arr[n - 1], i, n - 1) for i in range(n - 1)]
5 heapq.heapify(heap)
6 for _ in range(k - 1):
7 _, i, j = heapq.heappop(heap)
8 if j - 1 > i:
9 heapq.heappush(heap, (arr[i] / arr[j - 1], i, j - 1))
10 _, i, j = heap[0]
11 return [arr[i], arr[j]]1class Solution {
2 public int[] kthSmallestPrimeFraction(int[] arr, int k) {
3 int n = arr.length;
4 PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> arr[a[0]] * arr[b[1]] - arr[b[0]] * arr[a[1]]);
5 for (int i = 0; i < n - 1; i++) {
6 heap.offer(new int[]{i, n - 1});
7 }
8 for (int s = 0; s < k - 1; s++) {
9 int[] top = heap.poll();
10 if (top[1] - 1 > top[0]) {
11 heap.offer(new int[]{top[0], top[1] - 1});
12 }
13 }
14 int[] best = heap.peek();
15 return new int[]{arr[best[0]], arr[best[1]]};
16 }
17}1class Solution {
2public:
3 vector<int> kthSmallestPrimeFraction(vector<int>& arr, int k) {
4 int n = arr.size();
5 auto cmp = [&](const pair<int, int>& a, const pair<int, int>& b) {
6 return arr[a.first] * arr[b.second] > arr[b.first] * arr[a.second];
7 };
8 priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> heap(cmp);
9 for (int i = 0; i < n - 1; i++) {
10 heap.push({i, n - 1});
11 }
12 for (int s = 0; s < k - 1; s++) {
13 auto [i, j] = heap.top();
14 heap.pop();
15 if (j - 1 > i) {
16 heap.push({i, j - 1});
17 }
18 }
19 auto [i, j] = heap.top();
20 return {arr[i], arr[j]};
21 }
22};Time and space complexity
O((n + k) log n)
Seeding pushes n - 1 entries and each of the k - 1 pops does one pop and at most one push on a heap of size at most n.
O(n)
The heap holds at most one fraction per row.
Other approaches
Binary search on the value (time O(n log W), space O(1))
Guess a value x in (0, 1) and count fractions <= x with two pointers, tracking the largest such fraction. Narrow x until the count is exactly k.
Generate and sort (time O(n^2 log n), space O(n^2))
Build all n(n - 1) / 2 fractions and sort them. Simple, but too slow and memory hungry for n = 1000.
Common mistakes
- Moving the wrong way along a row: the next larger fraction in row i is over arr[j - 1], not arr[j + 1].
- Pushing every neighbour of a popped cell, as in a 2D grid search, which creates duplicates. One push per pop along the row is enough.
- Popping k times instead of k - 1 and then reading the top, which returns the (k + 1)th fraction.
- Comparing with integer division, which turns every fraction into 0.
Frequently asked questions
Why does the heap only need one fraction per row?
A row is sorted, so its next fraction cannot come out before the one in front of it. Keeping just the front of each row is enough to always know the global minimum.
Is floating point safe here?
The values are at most 30000, so two different fractions differ by at least about 1e-9, which doubles separate easily. Cross-multiplying keeps everything in integers anyway, and the products stay below 2^31.
Why do the primes matter?
Distinct primes guarantee that no two fractions are equal, so the kth smallest is unique and the heap never has to break ties.
When is binary search better?
When k is close to n^2 / 2 the heap does many pops. Binary search on the value costs O(n) per guess no matter how big k is.