Back to questions
Given an integer , generate all simplified fractions between and (exclusive) where the denominator is less than or equal to . A fraction is simplified if the numerator and denominator have no common divisors other than .
Return a sorted list of fractions, where each fraction is represented as .
For example:
The simplest way to generate all unique fractions between and with denominators up to is to use two nested loops to iterate through all possible numerators and denominators. For each fraction, we simplify it and only store unique results. Here’s how this approach works:
Here’s the code:
Please note: Some interviewer's may let you first write the solution using the function, but then force you to code it up manually without importing it. Be prepared to have to code this up!
To further optimize this approach, we can avoid using a set by only adding fractions that are already in their simplest form. If a fraction has a GCD of , it means the fraction is in its simplest form, so we don’t need to simplify or check for duplicates. Here’s how it works:
This avoids duplicate fractions without the need for a set. Additionally, because we are iterating from smaller to larger numerators and denominators, the fractions remain in ascending order, eliminating the need for additional sorting.
Whenever a fraction isn’t in its simplest form (i.e., its GCD is greater than ), simplifying it will yield an equivalent fraction where both the numerator and denominator are smaller. This simplified version would already have been explored earlier in the loop since we iterate from the smallest numerators and denominators upwards.
For example, consider the fraction . Its GCD is , so we can simplify it by dividing both the numerator and denominator by :
Since we loop through numerators and denominators in ascending order, we would encounter (already in its simplest form) before reaching . By only adding fractions with a GCD of , we ensure that simplified versions like are already included in the result by the time we reach non-simplified ones like . This way, we avoid both unnecessary simplification and the need to check for duplicates.
Here’s the code: