Simplified Fractions — LeetCode 1447 Python Solution

MediumMathStringNumber Theory
Problem
#1447
Reading time
2 min

The problem

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. You can return the answer in any order.

Example

Input
n = 2
Output
["1/2"]
Explanation
"1/2" is the only unique fraction with a denominator less-than-or-equal-to 2.

Python solution

Python
class Solution:
    def simplifiedFractions(self, n: int) -> List[str]:
        return [
            f'{i}/{j}'
            for i in range(1, n)
            for j in range(i + 1, n + 1)
            if gcd(i, j) == 1
        ]

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1447. Simplified Fractions is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1447. Simplified Fractions?
LeetCode 1447. Simplified Fractions is rated Medium on LeetCode.
What topics does LeetCode 1447. Simplified Fractions cover?
LeetCode 1447. Simplified Fractions is tagged Math, String and Number Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview