MediumNo. 1447

Simplified Fractions — LeetCode 1447 Python Solution

Topics
Math, String, Number Theory
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

PythonSolution
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

Time
O(n) or O(1)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0043Multiply StringsMedium
0168Excel Sheet Column TitleEasy
0171Excel Sheet Column NumberEasy
0204Count PrimesMedium
0258Add DigitsEasy
0273Integer to English WordsHard

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.

Free to download. Check it runs on your machine, then pick a plan.