Problem 786

Abstract / Summary

Find the kth smallest fraction formed by dividing one prime by a larger prime from given lists.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0786.py

class Solution:
    def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:
        # convert all to the same denominator
        primes = [ 2 ]
        for n in range(3, 1000, 2):
            i = n
            for j in primes:
                while i % j == 0:
                    i //= j
            if i > 1:
                primes.append(n)

        de = 1
        for i in primes:
            de *= i

        all = { }
        for i in range(len(arr)):
            for j in range(i+1, len(arr)):
                ii = arr[i]
                jj = arr[j]
                scaled = ii * de // jj
                all[scaled] = [ ii, jj ]

        keys = sorted(all.keys());
        return all[keys[k-1]]
26 lines | 747 bytes | submitted August 15, 2023 | GitHub   4% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Heap (Priority Queue)
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that returns the k-th smallest fraction formed by two distinct elements of a sorted integer array, where each fraction is expressed as a pair [numerator, denominator]. The algorithm proceeds in four logical phases: generation of a prime list, construction of a common denominator, enumeration and scaling of all possible fractions, and selection of the required fraction after sorting the scaled values.

Prime List Generation

The first phase builds a list of odd prime numbers up to 999. The code starts with the prime 2 already present and then iterates over odd candidates. For each candidate n the inner loop attempts division by every previously discovered prime. Whenever a divisor evenly divides the candidate, the candidate is reduced by that divisor repeatedly. After the inner loop, a residual value greater than one indicates that the candidate has no prime divisor among the collected primes, and therefore it is appended to the list.

primes = [2]
for n in range(3, 1000, 2):
    i = n
    for j in primes:
        while i % j == 0:
            i //= j
    if i > 1:
        primes.append(n)

Edge handling - The loop skips even numbers, guaranteeing that only odd candidates are examined. The inner while loop removes all occurrences of a prime factor, ensuring that composite numbers with repeated factors are correctly reduced to a non-prime remainder.

Common Denominator Construction

Having obtained the prime list, the algorithm computes a single large denominator by multiplying all primes together. This product, stored in de, serves as a common scaling factor for every fraction generated later.

de = 1
for i in primes:
    de *= i

Edge handling - The multiplication starts from 1, so an empty prime list (which cannot occur because 2 is always present) would leave de as 1, preserving correctness for degenerate inputs.

Fraction Enumeration and Scaling

The core of the method iterates over all ordered pairs (i, j) with i < j. For each pair it extracts the corresponding array values ii and jj. The fraction ii / jj is scaled to an integer by multiplying the numerator ii with the common denominator de and performing integer division by the denominator jj. The scaled integer serves as a sortable key, while the original numerator and denominator are stored as the value in a dictionary all.

all = {}
for i in range(len(arr)):
    for j in range(i + 1, len(arr)):
        ii = arr[i]
        jj = arr[j]
        scaled = ii * de // jj
        all[scaled] = [ii, jj]

Edge handling - The double loop respects the condition i < j, guaranteeing that each fraction uses distinct elements and that the numerator is always less than the denominator because the input array is sorted in ascending order. The integer division // ensures that the scaled key is an exact integer, avoiding floating-point inaccuracies.

Selection of the k-th Smallest Fraction

After all fractions have been enumerated, the dictionary keys are extracted, sorted, and the k-th smallest key (using zero-based indexing) is used to retrieve the corresponding fraction from the dictionary.

keys = sorted(all.keys())
return all[keys[k - 1]]

Edge handling - The expression k - 1 correctly maps a one-based k to the zero-based index used by Python lists. The code assumes that k is within the valid range 1 … nC2, where n is the length of arr; the sorted key list will contain exactly the number of distinct fractions generated, so indexing is safe under that precondition.

Performance Optimizations

The algorithm incorporates several choices that reduce computational overhead.

The prime generation step limits the search space to odd numbers below 1000, avoiding unnecessary checks on even numbers and large composites. By dividing out all occurrences of a prime factor in the inner loop, the algorithm quickly discards non-prime candidates without needing a full trial division up to the square root of each number.

The use of a single common denominator de allows each fraction to be represented by a single integer scaled. This eliminates the need for pairwise fraction comparison during sorting, because integer keys can be sorted directly by Python’s highly optimized Timsort algorithm.

Storing the scaled value as a dictionary key provides O(1) average-time retrieval of the original numerator and denominator once the sorted order is known. This avoids a secondary pass to reconstruct the fraction after sorting.

Multiplying all primes together yields a denominator that is guaranteed to be a multiple of any possible denominator from the input array, ensuring that the scaling operation never loses precision.

Overall, the design leverages integer arithmetic, precomputed prime factors, and dictionary lookups to keep the heavy work confined to phases that benefit from Python’s built-in optimizations.

written by openai gpt

ELI5 - Simplified Explanation

Imagine that every number in the list is like a piece of a fraction, where one number sits on top of another. To figure out which fraction is the smallest, the code first finds a very big super number that can be divided by all the denominators. This makes it easier to compare the fractions by turning them into whole numbers. After that, it looks at every possible pair of numbers in the list and creates a fraction from them. Each fraction is turned into a new, bigger number using that super number so that they are all easy to line up in order from smallest to biggest. Finally, the code puts all these new numbers in a row, like toys on a shelf from tiniest to tallest, and picks out the one that is at the special spot determined by the letter k.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 3 | μ = 3.41 | σ = 1.77

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
halfrost Go
JoshCrozier JS
keineahnung2345 C++
ruoru Rust
suxrobGM C#
trung-hn Python
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
ruoru Rust
suxrobGM C#
trung-hn Python
wisdompeak C++
27 links | 15 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality