MediumNo. 0592

Fraction Addition and Subtraction — LeetCode 592 Python Solution

Topics
Math, String, Simulation
Reading time
3 min

The problem

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.

Example

Input
expression = "-1/2+1/2"
Output
"0/1"

Python solution

PythonSolution
class Solution:
    def fractionAddition(self, expression: str) -> str:
        x, y = 0, 6 * 7 * 8 * 9 * 10
        if expression[0].isdigit():
            expression = '+' + expression
        i, n = 0, len(expression)
        while i < n:
            sign = -1 if expression[i] == '-' else 1
            i += 1
            j = i
            while j < n and expression[j] not in '+-':
                j += 1
            s = expression[i:j]
            a, b = s.split('/')
            x += sign * int(a) * y // int(b)
            i = j
        z = gcd(x, y)
        x //= z
        y //= z
        return f'{x}/{y}'

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 592. Fraction Addition and Subtraction is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

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
0412Fizz BuzzEasy
0415Add StringsEasy
0537Complex Number MultiplicationMedium
0640Solve the EquationMedium
1041Robot Bounded In CircleMedium

Frequently asked questions

How hard is LeetCode 592. Fraction Addition and Subtraction?

LeetCode 592. Fraction Addition and Subtraction is rated Medium on LeetCode.

What topics does LeetCode 592. Fraction Addition and Subtraction cover?

LeetCode 592. Fraction Addition and Subtraction is tagged Math, String and Simulation 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.