> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Fraction Addition and Subtraction

> Tested Python solution for LeetCode 592 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 592, [Medium](/catalog/medium). Topics: [Math](/catalog/topics/math), [String](/catalog/topics/string), [Simulation](/catalog/topics/simulation), Euclidean Algorithm, Greatest Common Divisor. [View on LeetCode](https://leetcode.com/problems/fraction-addition-and-subtraction/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 592   # by problem number
lcpy gen -s fraction_addition_and_subtraction   # by problem name
```

## 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. 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`.

### Examples

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

```
Input: expression = "-1/2+1/2+1/3"
Output: "1/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.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/fraction_addition_and_subtraction/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/fraction_addition_and_subtraction/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def fraction_addition(self, expression: str) -> str:
        num, den = 0, 1
        i, n = 0, len(expression)
        while i < n:
            sign = 1
            if expression[i] in "+-":
                if expression[i] == "-":
                    sign = -1
                i += 1
            numerator = 0
            while i < n and expression[i].isdigit():
                numerator = numerator * 10 + int(expression[i])
                i += 1
            i += 1  # skip '/'
            denominator = 0
            while i < n and expression[i].isdigit():
                denominator = denominator * 10 + int(expression[i])
                i += 1
            num = num * denominator + sign * numerator * den
            den *= denominator
        if num == 0:
            return "0/1"
        a, b = abs(num), den
        while b:
            a, b = b, a % b
        return f"{num // a}/{den // a}"
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.