K-th Smallest Prime Fraction - Problem

You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.

For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].

Return the k-th smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].

Input & Output

Example 1 — Basic Case
$ Input: arr = [1,2,3,5], k = 3
Output: [2,5]
💡 Note: All fractions: 1/2, 1/3, 1/5, 2/3, 2/5, 3/5. Sorted: 1/5, 1/3, 2/5, 1/2, 3/5, 2/3. The 3rd smallest is 2/5.
Example 2 — Different K Value
$ Input: arr = [1,7], k = 1
Output: [1,7]
💡 Note: Only one fraction possible: 1/7, so the 1st smallest is 1/7.
Example 3 — Larger Array
$ Input: arr = [1,2,3,5,7], k = 4
Output: [1,3]
💡 Note: All fractions in ascending order: 1/7, 1/5, 2/7, 1/3, 1/2, 2/5, 3/7, 3/5, 2/3, 5/7. The 4th smallest fraction is 1/3.

Constraints

  • 2 ≤ arr.length ≤ 1000
  • 1 ≤ arr[i] ≤ 3 × 104
  • arr[0] == 1
  • arr[i] is a prime number for i > 0
  • All the numbers of arr are unique and sorted in ascending order
  • 1 ≤ k ≤ arr.length × (arr.length - 1) / 2

Visualization

Tap to expand
K-th Smallest Prime Fraction INPUT Sorted Prime Array: 1 i=0 2 i=1 3 i=2 5 i=3 All Possible Fractions (i < j): 1/2 = 0.500 1/3 = 0.333 1/5 = 0.200 2/3 = 0.667 2/5 = 0.400 3/5 = 0.600 Sorted Order: 1. 1/5 = 0.200 2. 1/3 = 0.333 3. 2/5 = 0.400 (k=3) 4. 1/2 = 0.500 5. 3/5 = 0.600 6. 2/3 = 0.667 arr=[1,2,3,5], k=3 ALGORITHM STEPS 1 Binary Search Setup lo=0, hi=1 (fraction range) 2 Calculate Mid mid = (lo + hi) / 2 3 Count Fractions Count fractions <= mid Track max fraction found 4 Adjust Bounds if count < k: lo = mid if count >= k: hi = mid Binary Search on Value [0.0] ----mid---- [1.0] O(n log n * log(max)) When count == k: Return max fraction found FINAL RESULT K-th (3rd) Smallest Fraction: 2 5 = 0.400 Output Array: [2, 5] Verification: Fractions smaller than 2/5: 1/5, 1/3 (2 fractions) OK - 2/5 is 3rd smallest Key Insight: Binary search on the answer value (0 to 1) instead of indices. For each mid value, count how many fractions are smaller using two pointers. When exactly k fractions are found less than or equal to mid, return the largest fraction seen. Time: O(n log(max_val)), Space: O(1). TutorialsPoint - K-th Smallest Prime Fraction | Optimal Solution
Asked in
Google 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen