Approaches

💡

Intuition

Time O(n² log n)Space O(n²)

We can generate all possible fractions from the given array and sort them to find the k-th smallest. This is straightforward but inefficient for larger arrays.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty list to store all fractions.
  2. 2Step 2: Use two nested loops to iterate through the array, generating fractions arr[i] / arr[j] for all valid pairs (i, j).
  3. 3Step 3: Sort the list of fractions and return the k-th smallest fraction.
solution.py10 lines
1# Full working Python code
2arr = [1, 2, 3, 5]
3k = 3
4fractions = []
5for i in range(len(arr)):
6    for j in range(i + 1, len(arr)):
7        fractions.append((arr[i], arr[j]))
8fractions.sort(key=lambda x: x[0] / x[1])
9result = fractions[k - 1]
10print(result)

Complexity note: The time complexity is O(n²) for generating fractions and O(n² log n) for sorting them. Space complexity is O(n²) due to storing all fractions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.