K-th Smallest Prime Fraction - Problem
K-th Smallest Prime Fraction
You're given a sorted array containing
For every pair of indices
Example: For array
You're given a sorted array containing
1 and prime numbers, where all integers are unique. Your task is to find the k-th smallest fraction formed by dividing any element by a larger element in the array.For every pair of indices
i and j where 0 <= i < j < arr.length, we can form the fraction arr[i] / arr[j]. Among all such fractions, return the k-th smallest one as an array [numerator, denominator].Example: For array
[1, 2, 3, 5], possible fractions are: 1/2, 1/3, 1/5, 2/3, 2/5, 3/5. If k=3, we return [2, 5] since 2/5 is the 3rd smallest fraction. Input & Output
example_1.py โ Basic Case
$
Input:
arr = [1, 2, 3, 5], k = 3
โบ
Output:
[2, 5]
๐ก Note:
All fractions in ascending order: 1/5, 1/3, 2/5, 1/2, 3/5, 2/3. The 3rd fraction is 2/5.
example_2.py โ First Fraction
$
Input:
arr = [1, 7], k = 1
โบ
Output:
[1, 7]
๐ก Note:
Only one fraction possible: 1/7, so it's the 1st smallest.
example_3.py โ Larger Array
$
Input:
arr = [1, 2, 3, 5, 7], k = 5
โบ
Output:
[2, 7]
๐ก Note:
With 5 numbers, we have 10 possible fractions. The 5th smallest is 2/7.
Constraints
- 2 โค arr.length โค 1000
- 1 โค arr[i] โค 3 ร 104
- arr[0] == 1
- arr[i] is a prime number for i > 0
- All numbers in arr are unique and sorted in ascending order
- 1 โค k โค arr.length ร (arr.length - 1) / 2
Visualization
Tap to expand
Understanding the Visualization
1
Set Search Range
Initialize binary search bounds from 0 to 1 (all possible fraction values)
2
Count Efficiently
For each mid value, use two pointers to count fractions โค mid in O(n) time
3
Track Best Candidate
While counting, remember the largest fraction that's still โค mid
4
Narrow Search
Adjust search range based on whether we found too few or too many fractions
5
Find Exact Match
When count equals k, return the tracked best candidate fraction
Key Takeaway
๐ฏ Key Insight: Instead of generating all O(nยฒ) fractions, we binary search on the fraction value and use two pointers to count fractions โค target in O(n) time, achieving optimal O(n log(max_val)) complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code