LeetCode 1447: Simplified Fractions Solution

Master LeetCode problem 1447 (Simplified Fractions), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1447. Simplified Fractions

Problem Explanation

Explanation

To solve this problem, we can iterate over all possible numerators from 1 to n-1 and for each numerator, iterate over all possible denominators from numerator+1 to n. We check if the numerator and denominator are coprime (i.e., their greatest common divisor is 1). If they are coprime, we add the simplified fraction to our result list.

Algorithm

  1. Initialize an empty list result to store the simplified fractions.
  2. Iterate numerator from 1 to n-1.
    • For each numerator, iterate denominator from numerator+1 to n.
      • If gcd(numerator, denominator) is 1, then add the simplified fraction to result.
  3. Return the result.

Time Complexity

The time complexity of this algorithm is O(n^2) where n is the input integer.

Space Complexity

The space complexity is O(1) excluding the space required to store the result.

Solution Code

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<String> simplifiedFractions(int n) {
        List<String> result = new ArrayList<>();
        
        for (int numerator = 1; numerator < n; numerator++) {
            for (int denominator = numerator + 1; denominator <= n; denominator++) {
                if (gcd(numerator, denominator) == 1) {
                    result.add(numerator + "/" + denominator);
                }
            }
        }
        
        return result;
    }
    
    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1447 (Simplified Fractions)?

This page provides optimized solutions for LeetCode problem 1447 (Simplified Fractions) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1447 (Simplified Fractions)?

The time complexity for LeetCode 1447 (Simplified Fractions) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1447 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1447 in Java, C++, or Python.

Back to LeetCode Solutions