Leetcode 1447: Simplified Fractions

grid47
grid47
Exploring patterns and algorithms
Jun 15, 2024 6 min read

Given an integer n, return a list of all unique simplified fractions between 0 and 1 (exclusive) where the denominator is less than or equal to n. A fraction is simplified if the greatest common divisor (GCD) of the numerator and denominator is 1. The result can be returned in any order.
Problem
Approach
Steps
Complexity
Input: An integer `n` representing the maximum allowed value for the denominator.
Example: Input: n = 4
Constraints:
• 1 <= n <= 100
Output: A list of strings representing all unique simplified fractions between 0 and 1 with denominators up to `n`.
Example: Output: ["1/2", "1/3", "1/4", "2/3", "3/4"]
Constraints:
• The list can be in any order.
Goal: Generate all unique simplified fractions with denominators up to `n`.
Steps:
• Iterate through all possible denominators from 2 to `n`.
• For each denominator, iterate through numerators from 1 to denominator-1.
• Check if the GCD of the numerator and denominator is 1. If true, add the fraction to the result list.
Goal: Ensure all fractions are simplified and fit the conditions.
Steps:
• Fractions must be in their simplest form (GCD of numerator and denominator is 1).
• Only consider denominators up to `n`.
Assumptions:
• The denominator of the fraction is always greater than the numerator.
• Fractions must be strictly between 0 and 1.
Input: Input: n = 5
Explanation: Output: ["1/2", "1/3", "1/4", "1/5", "2/3", "2/5", "3/4", "3/5", "4/5"]. These are all the simplified fractions between 0 and 1 with denominators less than or equal to 5.

Input: Input: n = 2
Explanation: Output: ["1/2"]. Only one unique fraction exists with denominator less than or equal to 2.

Input: Input: n = 3
Explanation: Output: ["1/2", "1/3", "2/3"]. The fraction "2/3" is included as it is simplified and lies between 0 and 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus