Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Fraction Addition and Subtraction

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "592" 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 a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1. Example 1: Input: expression = "-1/2+1/2" Output: "0/1" Example 2: Input: expression = "-1/2+1/2+1/3" Output: "1/3" Example 3: Input: expression = "1/3-1/2" Output: "-1/6" Constraints: The input string only contains '0' to '9', '/', '+' and '-'. So does the output. Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted. The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above. The number of given fractions will be in the range [1, 10]. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.

Explanation

Here's a solution to the fraction addition and subtraction problem:

  • Parsing and Iteration: Parse the input string to extract numerators and denominators of each fraction along with their signs. Iterate through the fractions and perform the addition/subtraction sequentially.
  • GCD Reduction: After calculating the final numerator and denominator, find the greatest common divisor (GCD) and divide both numerator and denominator by GCD to make the fraction irreducible.
  • Output Formatting: Format the output string in "numerator/denominator" format. Handle integer results (denominator 1).

  • Runtime Complexity: O(N * log(M)), where N is the number of fractions and M is the maximum value of the numerator or denominator. The log(M) factor comes from the GCD calculation.

  • Storage Complexity: O(1). We use a constant amount of extra space.

Code

    import math

def fractionAddition(expression: str) -> str:
    """
    Calculates the result of fraction addition and subtraction expression.

    Args:
        expression: A string representing the expression.

    Returns:
        A string representing the calculation result in irreducible fraction format.
    """

    def gcd(a, b):
        """
        Calculates the greatest common divisor of two integers.
        """
        while b:
            a, b = b, a % b
        return a

    num = 0
    den = 1
    i = 0
    while i < len(expression):
        sign = 1
        if expression[i] == '+' or expression[i] == '-':
            if expression[i] == '-':
                sign = -1
            i += 1

        num1 = 0
        while i < len(expression) and expression[i].isdigit():
            num1 = num1 * 10 + int(expression[i])
            i += 1

        i += 1  # Skip '/'

        den1 = 0
        while i < len(expression) and expression[i].isdigit():
            den1 = den1 * 10 + int(expression[i])
            i += 1

        num1 = sign * num1

        new_num = num * den1 + num1 * den
        new_den = den * den1

        common_divisor = gcd(abs(new_num), new_den)
        num = new_num // common_divisor
        den = new_den // common_divisor

    return str(num) + "/" + str(den)

More from this blog

C

Chatmagic blog

2894 posts