Leetcode 786: K-th Smallest Prime Fraction

grid47
grid47
Exploring patterns and algorithms
Aug 20, 2024 6 min read

A set of fractions where the kth smallest prime fraction is found, glowing softly as it is identified.
Solution to LeetCode 786: K-th Smallest Prime Fraction Problem

You are given a sorted array of prime numbers and the number 1. You need to find the k-th smallest fraction formed by considering all possible fractions arr[i] / arr[j] where i < j. Return the k-th smallest fraction as an array of two integers, where arr[i] is the numerator and arr[j] is the denominator.
Problem
Approach
Steps
Complexity
Input: The input consists of a sorted array arr containing prime numbers and the number 1. You are also given an integer k.
Example: Input: arr = [1, 3, 5, 7], k = 4
Constraints:
• 2 <= arr.length <= 1000
• 1 <= arr[i] <= 30,000
• arr[0] == 1
• arr[i] is a prime number for i > 0
• 1 <= k <= arr.length * (arr.length - 1) / 2
Output: Return the k-th smallest fraction as an array of two integers. The first integer is the numerator and the second is the denominator of the fraction.
Example: Output: [3, 7]
Constraints:
• The output should be an array of two integers representing the k-th smallest fraction.
Goal: The goal is to find the k-th smallest fraction by considering all possible fractions in the form arr[i] / arr[j] where i < j.
Steps:
• Initialize a priority queue to store the fractions and their indices.
• Push fractions formed by arr[i] and arr[j] into the priority queue.
• Pop the fractions from the priority queue and keep track of the smallest fractions.
• Repeat until the k-th smallest fraction is found.
Goal: The input is a sorted array with prime numbers and the number 1. You need to find the k-th smallest fraction among all pairs i < j.
Steps:
• 2 <= arr.length <= 1000
• 1 <= arr[i] <= 30,000
• arr[0] == 1
• arr[i] is a prime number for i > 0
Assumptions:
• The array arr is sorted in strictly increasing order.
• The number of fractions is bounded by n * (n - 1) / 2.
Input: Example 1: Input: arr = [1, 3, 5, 7], k = 4
Explanation: The fractions to be considered in sorted order are: 1/7, 1/5, 1/3, 3/7, 5/7, and 3/5. The 4th smallest fraction is 3/7.

Input: Example 2: Input: arr = [1, 2, 7], k = 2
Explanation: The fractions to be considered are: 1/7, 1/2, and 2/7. The 2nd smallest fraction is 1/7.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus