Problem Description
Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. A fraction is considered simplified if the greatest common divisor (GCD) of its numerator and denominator is 1.
Key Insights
- Only consider denominators from 2 to n since fractions with denominator 1 (like 1/1) are not between 0 and 1.
- For each denominator, iterate over possible numerators from 1 up to denominator - 1.
- Use the GCD of numerator and denominator to check if the fraction is in simplified form.
- The overall time complexity is driven by the nested loop over denominators and numerators.
Space and Time Complexity
Time Complexity: O(n^2 * log(n)) – Iterating through all possible pairs (numerator, denominator) and performing a GCD computation which takes logarithmic time. Space Complexity: O(n^2) – In the worst case, storing up to O(n^2) fraction strings.
Solution
We iterate through all denominators d from 2 to n, and for each d, we iterate through all numerators from 1 to d - 1. For every fraction numerator/d, we check if the GCD of numerator and denominator is 1. If yes, then the fraction is simplified and we add it to our result list as a string "numerator/denom".
The algorithm primarily uses loops and a helper function (or method) for computing the GCD. The main gotcha is correctly checking that a fraction is in its simplest form by ensuring that the numerator and denominator are co-prime.