Statement▼
You are given a sorted array of unique integers, arr
, which includes the number
For every index arr.length
, you can form a fraction by taking the number at index arr[i] / arr[j]
.
Your task is to return the answer[0]
, is the numerator (arr[i]
), and the second element, answer[1]
, is the denominator (arr[j]
) corresponding to the
Constraints:
2≤ arr.length
≤103 1≤arr[i]≤3×104 arr[0]=1 arr[i] is a prime number fori>0. All the numbers of
arr
are unique and sorted in strictly increasing order.1≤k≤ arr.length
× (arr.length
−1 )
Solution
We need to find the
We first add the smallest possible fraction for each denominator into a heap. This fraction is formed by pairing the first element of the array with each later element. As the array is sorted, the smallest fraction for any denominator always has the first element as the numerator. Adding only these fractions ensures we process the smallest ones first.
Next, we repeatedly remove the smallest fraction from the heap. Each fraction belongs to a sequence where the denominator stays the same, but the numerator can increase. If a larger numerator exists in that sequence, we form the next fraction and insert it into the heap. This keeps the heap updated and ensures we always have the next smallest fraction available.
We repeat this process
Here are the detailed steps of the algorithm that we have just discussed:
We initialize an empty heap,
min_heap
, to store fractions in ascending order.Next, we iterate over the input array,
arr
, from index1 to n−1 (denoted byj ). For eacharr[j]
, we form the smallest possible fraction usingarr[0]
as the numerator andarr[j]
as the denominator. Asarr
is sorted, the smallest fraction for each denominator is alwaysarr[0] / arr[j]
.At each iteration, we store the following three values in the min heap:
A fraction value is denoted by
arr[0] / arr[j]
.A numerator index is initially set to
0 , referring toarr[0]
.A denominator index,
j , refers toarr[j]
.
The fractions are inserted into
min_heap
, using their values as keys.
To identify the
kth smallest fraction, we repeat the following processk−1 times:Extract the smallest fraction from
min_heap
, representing the next smallest fraction overall. Identify the numerator indexi
and denominator indexj
.If there is a larger fraction available from the same denominator group (
i + 1 < j
), computearr[i + 1] / arr[j]
and insert it intomin_heap
. This ensures the heap remains updated with the next candidate fraction.
After performing the above steps
k−1 times, we extract the top fraction frommin_heap
, which is thekth smallest fraction. So, we return its numerator and denominator as[arr[i], arr[j]]
.
The following illustration shows these steps in detail: