KatInterview

802. K-th Smallest Prime Fraction

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the k-th smallest fraction among all possible fractions arr[i] / arr[j] where i < j, given a sorted array arr of unique primes and the number 1. The brute-force approach would be to generate all O(n^2) fractions, sort them, and pick the k-th one. This would have a time complexity of O(n^2 log n), which might be too slow given n up to 1000. The follow-up question hints at a more efficient solution.

Solution

K-th Smallest Prime Fraction in Python

class Solution:
    def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:
        n = len(arr)
        low, high = 0.0, 1.0
        ans = [0, 1]

        # Binary search for the value of the k-th fraction.
        while high - low > 1e-9:
            mid = (low + high) / 2.0
            if mid == 0: # Avoid issues with mid being too small
                low = 1e-9
                continue
            
            # Count fractions <= mid and find the largest fraction among them.
            count = 0
            # p/q stores the largest fraction found so far that is <= mid
            p, q = 0, 1

            # Use two pointers (i, j) to count in O(n)
            i = 0
            for j in range(1, n):
                # For a fixed denominator arr[j], find how many numerators arr[i] satisfy
                # arr[i]/arr[j] <= mid, which is arr[i] <= mid * arr[j]
                while i < j and arr[i] <= mid * arr[j]:
                    i += 1
                count += i

                # If i > 0, arr[i-1]/arr[j] is the largest fraction with denominator arr[j] that is <= mid.
                if i > 0:
                    # Compare this fraction with our current max p/q
                    # Use cross-multiplication to avoid floating point issues.
                    if arr[i - 1] * q > p * arr[j]:
                        p, q = arr[i - 1], arr[j]

            if count >= k:
                # If count is k or more, mid is a potential answer or too high.
                # The largest fraction we found (p/q) is our current best candidate.
                # We try for a smaller value.
                ans = [p, q]
                high = mid
            else:
                # If count is less than k, mid is too small.
                low = mid

        return ans

K-th Smallest Prime Fraction in Java

class Solution {
    public int[] kthSmallestPrimeFraction(int[] arr, int k) {
        int n = arr.length;
        double low = 0.0, high = 1.0;
        int[] ans = {0, 1};

        // Binary search for the value of the k-th fraction.
        while (high - low > 1e-9) {
            double mid = low + (high - low) / 2.0;
            if (mid == 0) { // Avoid infinite loop if low and high are very small
                low = 1e-9;
                continue;
            }
            
            // Count fractions <= mid and find the largest fraction among them.
            int count = 0;
            int p = 0, q = 1; // Numerator and denominator of the max fraction <= mid

            // Use two pointers (i, j) to count in O(n)
            int i = 0;
            for (int j = 1; j < n; j++) {
                // For a fixed j, find the number of i's such that arr[i]/arr[j] <= mid
                // which is arr[i] <= mid * arr[j]
                while (i < j && arr[i] <= mid * arr[j]) {
                    i++;
                }
                count += i;
                // If i > 0, arr[i-1]/arr[j] is the largest fraction with denominator arr[j] that is <= mid.
                if (i > 0) {
                    // Compare this fraction with our current max p/q
                    // Use cross-multiplication to avoid floating point issues and use long to prevent overflow
                    if ((long) arr[i - 1] * q > (long) p * arr[j]) {
                        p = arr[i - 1];
                        q = arr[j];
                    }
                }
            }

            if (count >= k) {
                // If count is k or more, mid is a potential answer or too high.
                // The largest fraction we found (p/q) is our current best candidate.
                // We try for a smaller value.
                ans[0] = p;
                ans[1] = q;
                high = mid;
            } else {
                // If count is less than k, mid is too small.
                low = mid;
            }
        }

        return ans;
    }
}

K-th Smallest Prime Fraction in C++

class Solution {
public:
    vector<int> kthSmallestPrimeFraction(vector<int>& arr, int k) {
        int n = arr.size();
        double low = 0.0, high = 1.0;
        vector<int> ans = {0, 1};

        // Binary search for the value of the k-th fraction.
        while (high - low > 1e-9) {
            double mid = low + (high - low) / 2.0;
            if (mid == 0) { // Avoid infinite loop if low and high are very small
                low = 1e-9;
                continue;
            }
            
            // Count fractions <= mid and find the largest fraction among them.
            int count = 0;
            int p = 0, q = 1; // Numerator and denominator of the max fraction <= mid

            // Use two pointers (i, j) to count in O(n)
            int i = 0;
            for (int j = 1; j < n; ++j) {
                // For a fixed j, find the number of i's such that arr[i]/arr[j] <= mid
                // which is arr[i] <= mid * arr[j]
                while (i < j && arr[i] <= mid * arr[j]) {
                    i++;
                }
                count += i;
                // If i > 0, arr[i-1]/arr[j] is the largest fraction with denominator arr[j] that is <= mid.
                if (i > 0) {
                    // Compare this fraction with our current max p/q
                    // Use cross-multiplication to avoid floating point issues and use long long to prevent overflow
                    if ((long long)arr[i - 1] * q > (long long)p * arr[j]) {
                        p = arr[i - 1];
                        q = arr[j];
                    }
                }
            }

            if (count >= k) {
                // If count is k or more, mid is a potential answer or too high.
                // The largest fraction we found (p/q) is our current best candidate.
                // We try for a smaller value.
                ans = {p, q};
                high = mid;
            } else {
                // If count is less than k, mid is too small.
                low = mid;
            }
        }

        return ans;
    }
};

K-th Smallest Prime Fraction in TypeScript

function kthSmallestPrimeFraction(arr: number[], k: number): number[] {
    const n = arr.length;
    let low = 0.0, high = 1.0;
    let ans: number[] = [0, 1];

    // Binary search for the value of the k-th fraction.
    while (high - low > 1e-9) {
        let mid = low + (high - low) / 2.0;
        if (mid === 0) { // Avoid issues with mid being too small
            low = 1e-9;
            continue;
        }
        
        // Count fractions <= mid and find the largest fraction among them.
        let count = 0;
        let p = 0, q = 1; // Numerator and denominator of the max fraction <= mid

        // Use two pointers (i, j) to count in O(n)
        let i = 0;
        for (let j = 1; j < n; j++) {
            // For a fixed j, find the number of i's such that arr[i]/arr[j] <= mid
            // which is arr[i] <= mid * arr[j]
            while (i < j && arr[i] <= mid * arr[j]) {
                i++;
            }
            count += i;
            // If i > 0, arr[i-1]/arr[j] is the largest fraction with denominator arr[j] that is <= mid.
            if (i > 0) {
                // Compare this fraction with our current max p/q
                // Use cross-multiplication to avoid floating point issues.
                if (arr[i - 1] * q > p * arr[j]) {
                    p = arr[i - 1];
                    q = arr[j];
                }
            }
        }

        if (count >= k) {
            // If count is k or more, mid is a potential answer or too high.
            // The largest fraction we found (p/q) is our current best candidate.
            // We try for a smaller value.
            ans = [p, q];
            high = mid;
        } else {
            // If count is less than k, mid is too small.
            low = mid;
        }
    }

    return ans;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.