You are given a sorted list of numbers arr
and two integers A
and B
. arr
represents the list of prime numbers. You need to find the A/B
th smallest prime fraction. A prime fraction in this context is a fraction arr[i]/arr[j]
where 0 <= i < j < arr.length
.
A/B
a guaranteed valid fraction with respect to the list length?
A
and B
are such that a valid fraction exists.arr[i]
with every other element arr[j]
, initializing the heap.arr[i]/arr[j]
in the min-heap, keep track of the indices.K-1
times.import heapq
def kthSmallestPrimeFraction(arr, k):
# Create a min-heap
heap = []
n = len(arr)
# Initial population of heap with smallest fractions (first element paired with each other)
for j in range(1, n):
heapq.heappush(heap, (arr[0] / arr[j], 0, j))
# Extract k-1 elements from the heap
for _ in range(k - 1):
fraction, i, j = heapq.heappop(heap)
# If i can be incremented (staying within bounds), push the next fraction
if i + 1 < j:
heapq.heappush(heap, (arr[i + 1] / arr[j], i + 1, j))
# The k-th smallest fraction
fraction, i, j = heapq.heappop(heap)
return [arr[i], arr[j]]
# Example usage
arr = [1, 2, 3, 5]
A = 3
B = 7
print(kthSmallestPrimeFraction(arr, A * B)) # Output: [2, 5]
n-1
elements initially.k-1
times.This approach ensures that the solution is optimized for the problem constraints and efficiently finds the k-th smallest prime fraction.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?