K-th Smallest Prime Fraction solution explained

K-th Smallest Prime Fraction gives a sorted array made of 1 and distinct primes and asks for the k-th smallest fraction arr[i] / arr[j] with i < j, returned as the pair [arr[i], arr[j]]. Treat each denominator as a sorted row of fractions and pop the k smallest from a min-heap, in O((n + k) log n). For large k, binary search on the fraction's value and count how many fractions fall below it with two pointers, in O(n log(1 / precision)).

By Published 9 min read

The problem, in plain terms

You get a strictly increasing array whose first element is 1 and whose other elements are prime numbers. Form every fraction arr[i] / arr[j] with i < j, so every fraction is below 1. Sort them in your head from smallest to largest and return the k-th one, as a two-element array of its numerator and denominator. Because all values are 1 or distinct primes, no two of these fractions are equal, so "the k-th smallest" is never ambiguous.

arr = [1, 3, 5, 11]

all fractions, smallest first:
  1/11 = 0.0909
  1/5  = 0.2
  3/11 = 0.2727
  1/3  = 0.3333    <- k = 4
  5/11 = 0.4545
  3/5  = 0.6

k = 4  ->  answer [1, 3]
One array, made up for this page

Notice that 3/11 comes before 1/3 even though its numerator is larger. Neither the numerator nor the denominator alone orders the list, which is what makes this harder than it looks. But fix a denominator, say 11, and the row 1/11, 3/11, 5/11 is in order. That observation drives both fast solutions.

Worth confirming: is k at most n × (n - 1) / 2, the number of fractions? Should the answer be the pair or the decimal value? How large are the primes, which decides how careful you need to be with floating point?

Why interviewers pick it

It tests whether you can see a set of sorted rows where none is given, and it has two respectable optimal answers. Strong candidates usually propose the heap first, then, if pushed on large k, the binary search on the answer, and they talk about precision without being asked. It pairs naturally with the k-pairs problem, which uses the same frontier on sums.

Brute force: list and sort everything

Generate all n × (n - 1) / 2 fractions and sort them. Using exact fractions avoids any floating-point doubt, which is why this was the reference for testing the two faster versions below. It takes O(n² log n) time and O(n²) memory.

from fractions import Fraction


def kth_fraction_slow(arr, k):
    pairs = [(arr[i], arr[j]) for j in range(len(arr)) for i in range(j)]
    pairs.sort(key=lambda p: Fraction(p[0], p[1]))
    return list(pairs[k - 1])
Python: sort every fraction exactly. O(n² log n) time.

Approach 1: a min-heap over the rows

Each denominator j defines a row: arr[0]/arr[j], arr[1]/arr[j], up to arr[j - 1]/arr[j], increasing. Push the first fraction of every row into a min-heap. Pop the smallest, and if its row has a next numerator, push that. After k - 1 pops, the top of the heap is the k-th smallest. It is the same frontier idea as merging sorted lists.

import heapq


def kth_fraction(arr, k):
    heap = [(arr[0] / arr[j], 0, j) for j in range(1, len(arr))]
    heapq.heapify(heap)
    for _ in range(k - 1):
        _, i, j = heapq.heappop(heap)
        if i + 1 < j:
            heapq.heappush(heap, (arr[i + 1] / arr[j], i + 1, j))
    _, i, j = heap[0]
    return [arr[i], arr[j]]
Python: heap of (value, numerator index, denominator index). O((n + k) log n) time, O(n) memory.

The heap compares floating-point quotients. That is safe here because two different fractions with denominators up to a few tens of thousands differ by far more than a double's rounding error. If you prefer exactness, compare p1 × q2 with p2 × q1 using integers, which is what the slow reference effectively does.

Approach 2: binary search on the value

Pick a candidate value mid between 0 and 1. Count how many fractions are at most mid, and remember the largest of them. If the count is exactly k, that largest fraction is the answer. If the count is below k, the answer is bigger, so search above mid; otherwise search below. Counting is linear with two pointers: as the numerator index i moves right, the first denominator index j with arr[i] / arr[j] ≤ mid can only move right too, and every denominator from j to the end also works.

function kthFraction(arr, k) {
  const n = arr.length;
  let lo = 0, hi = 1;
  for (;;) {
    const mid = (lo + hi) / 2;
    let count = 0, p = 0, q = 1, j = 1;
    for (let i = 0; i < n - 1; i++) {
      while (j < n && arr[i] > mid * arr[j]) j++;
      if (j === n) break;
      count += n - j;
      if (arr[i] * q > p * arr[j]) { p = arr[i]; q = arr[j]; } // keep the largest fraction <= mid
    }
    if (count === k) return [p, q];
    if (count < k) lo = mid; else hi = mid;
  }
}
JavaScript: binary search on the value with a two-pointer count. O(n) per step.

Why it stops: the fractions are distinct, so there is a gap between the k-th and the (k + 1)-th. Halving the interval eventually lands mid inside that gap, and then the count is exactly k. Each halving gains one bit, so the number of rounds is about the log of one over the smallest gap. With primes in the tens of thousands, that is a few dozen rounds of O(n) work. The comparison inside the loop uses cross-multiplication, so picking the largest fraction is exact even though mid is not.

Complexity summary

n values, the k-th smallest of n(n - 1)/2 fractions
ApproachTimeExtra memoryBest when
Sort every fractionO(n² log n)O(n²)Tiny inputs, testing
Min-heap over rowsO((n + k) log n)O(n)k is modest
Binary search on valueO(n × rounds), rounds ≈ log of 1 / smallest gapO(1)k is large, close to n²
n values, the k-th smallest of n(n - 1)/2 fractions. Scroll sideways on a small screen.

Edge cases to try

  • Two elements: there is one fraction, and k must be 1.
  • k = 1: the answer is 1 over the largest element.
  • k equal to the total count: the largest fraction, which is the biggest ratio of neighbors arr[i] / arr[i + 1]. It is not always the last two values: in the example above it is 3/5, not 5/11.
  • Large primes close together, where fractions are near each other: a good precision test for the binary search.
  • An array of just [1, p]: both approaches should return [1, p].

Mistakes to avoid

  • Popping k times from the heap instead of k - 1 and then reading the top, an off-by-one that returns the (k + 1)-th fraction.
  • Letting a row run past its own denominator (numerator index i reaching j), which adds fractions equal to or above 1.
  • Comparing fractions with == on floats while searching for an exact match to mid.
  • Resetting the j pointer for every i in the count, turning O(n) into O(n²) per round.
  • Using integer division in the comparison, which makes every fraction 0.

Follow-ups

  • The values are arbitrary positive integers. Equal fractions can now appear. The heap works unchanged, but the binary search needs a new stopping rule, because the count can jump from below k to above k without ever equaling it. Search for the smallest value whose count is at least k instead.
  • Return the k-th largest instead. Use the k-th smallest with k replaced by the total minus k plus one.
  • Avoid floating point entirely. A Stern-Brocot style search over fractions, or the heap with integer cross-multiplication, keeps everything exact.
  • Several queries for different k. If memory allows, sort once; otherwise run the binary search per query.

How to explain it out loud

Fictional example

Two answers, and when to use each
Candidate
There are about n squared over two fractions, so sorting them all is my baseline. But for a fixed denominator the fractions are already sorted by numerator, so I really have n - 1 sorted rows.
Candidate
Merging sorted rows is a heap job: seed with each row's smallest fraction, pop k - 1 times, push the next fraction from the popped row, and read the top. That is O((n + k) log n).
Interviewer
What if k is close to n squared?
Candidate
Then I would binary search on the value instead. For a guess mid, two pointers count fractions at or below it in linear time and remember the largest one. When the count equals k, that one is the answer.
Candidate
All the fractions are distinct, so there is a gap after the k-th one and the search is guaranteed to land in it.

Find K Pairs with Smallest Sums is the same heap frontier on a grid of sums, and the closest sibling of this problem. Minimum Cost to Hire K Workers is another problem built around ratios, sorted by cross-multiplication. Logger Rate Limiter is a lighter design question for a change of pace. The algorithm interview questions guide covers binary search on the answer more generally.

Practicing it with Natively

Since this problem has two good answers, practice choosing between them out loud. On Mac or Windows, Natively can read the problem from a screenshot during a practice session and lay out both the heap and the binary search with their costs, and the transcript of your mock round shows whether you mentioned precision before the interviewer did. The AI interview assistant page covers how practice works.

Questions people ask

How do you solve K-th Smallest Prime Fraction?

Treat each denominator as a row of fractions sorted by numerator. Push the first fraction of every row into a min-heap, pop k - 1 times while pushing the next fraction from the popped row, and return the fraction on top.

What is the time complexity of K-th Smallest Prime Fraction?

The heap approach is O((n + k) log n) with O(n) memory. Binary search on the value costs O(n) per round with a two-pointer count, and the number of rounds depends on the smallest gap between fractions.

How does the binary search version work?

Guess a value between 0 and 1, count how many fractions are at most that value with two pointers, and remember the largest such fraction. If the count is exactly k, return it; if it is less, search higher; otherwise search lower.

Why does K-th Smallest Prime Fraction use primes?

With 1 and distinct primes, no two fractions are equal, so the k-th smallest is unique and the binary search always finds a value with a count of exactly k.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP