Leetcode #592: Fraction Addition and Subtraction
In this guide, we solve Leetcode #592 Fraction Addition and Subtraction in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Math, String, Simulation
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: expression = "-1/2+1/2"
Output: "0/1"
Python Solution
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
The time complexity is O(n) or O(1). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.