K-th Smallest Prime Fraction (LeetCode 786): Solution and Explanation

Medium
Array
Two pointers
Binary search
Sorting
Heap (priority queue)

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

  1. Push (i, n - 1) for every row i < n - 1, ordered by arr[i] / arr[n - 1].
  2. Repeat k - 1 times: pop the smallest (i, j); if j - 1 > i, push (i, j - 1).
  3. Return [arr[i], arr[j]] for the heap top.
  4. 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
  1. Seed the heap with 1/5, 2/5 and 3/5.
  2. Pop 1/5 (first). Row 0 moves left: push 1/3.
  3. Pop 1/3 (second). Row 0 moves left: push 1/2.
  4. Two pops are done. The heap holds 2/5, 1/2 and 3/5, and its top 2/5 is the third smallest.
  5. 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]]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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.