#1447

Simplified Fractions

Medium
MathStringNumber TheoryNumber TheoryGCDFractions
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal solution leverages the properties of fractions and uses a mathematical approach to generate only the simplified fractions without checking each one. This is more efficient and avoids unnecessary calculations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty list to store the simplified fractions.
  2. 2Step 2: Loop through all denominators from 2 to n.
  3. 3Step 3: For each denominator, loop through numerators from 1 to (denominator - 1).
  4. 4Step 4: Use the GCD to check if the fraction is simplified. If GCD(numerator, denominator) is 1, add it to the list.
  5. 5Step 5: Return the list of simplified fractions.
solution.py5 lines
1# Full working Python code
2from math import gcd
3
4def simplifiedFractions(n):
5    return [f'{numerator}/{denominator}' for denominator in range(2, n + 1) for numerator in range(1, denominator) if gcd(numerator, denominator) == 1]

Complexity note: The time complexity remains O(n²) due to the nested loops, but we are more efficient in checking and storing results. The space complexity is O(n) as we store the results in a list.

  • 1Understanding GCD is crucial for identifying simplified fractions.
  • 2Recognizing patterns in fraction generation helps optimize the solution.

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