Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Simplified Fractions

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1447" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 1: Input: n = 2 Output: ["1/2"] Explanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2. Example 2: Input: n = 3 Output: ["1/2","1/3","2/3"] Example 3: Input: n = 4 Output: ["1/2","1/3","1/4","2/3","3/4"] Explanation: "2/4" is not a simplified fraction because it can be simplified to "1/2". Constraints: 1 <= n <= 100

Explanation

Here's the approach to solve this problem:

  • Iterate through denominators: Loop from 2 to n (inclusive), as the denominator must be greater than 1.
  • Iterate through numerators: For each denominator, loop from 1 to denominator - 1, representing the possible numerators.
  • Check for simplification (GCD): For each numerator/denominator pair, calculate the greatest common divisor (GCD). If the GCD is 1, the fraction is simplified, and add it to the result.

  • Runtime Complexity: O(n2 * log(n)), Storage Complexity: O(n2)

Code

    from math import gcd

def simplifiedFractions(n: int) -> list[str]:
    """
    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.
    """
    result = []
    for denominator in range(2, n + 1):
        for numerator in range(1, denominator):
            if gcd(numerator, denominator) == 1:
                result.append(f"{numerator}/{denominator}")
    return result

More from this blog

C

Chatmagic blog

2894 posts