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]]
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 719: Find K-th Smallest Pair Distance
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- 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