Fraction Addition and Subtraction — LeetCode 592 Python Solution
- Problem
- #592
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
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
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.