Fraction Addition and Subtraction

The problem is about performing fraction addition and subtraction based on the given string expression. The result should be in irreducible fraction form.

To solve this problem, we can follow these steps:

  1. Split the expression by “+” and “-” to extract individual fractions.
  2. Calculate the LCM (Least Common Multiple) of the denominators to find a common denominator.
  3. Convert each fraction to have the common denominator, and sum the numerators.
  4. Reduce the final fraction to its simplest form.

Here is the code to implement these steps:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from math import gcd

class Solution:
    def fractionAddition(self, expression: str) -> str:
        fractions = []
        i = 0
        for j in range(1, len(expression)):
            if expression[j] in '+-':
                fractions.append(expression[i:j])
                i = j
        fractions.append(expression[i:])

        numerator = 0
        LCM_denominator = 1

        # Calculate LCM of denominators and sum the numerators
        for fraction in fractions:
            num, denom = map(int, fraction.split('/'))
            common_gcd = gcd(LCM_denominator, denom)
            LCM_denominator *= denom // common_gcd
        for fraction in fractions:
            num, denom = map(int, fraction.split('/'))
            numerator += num * (LCM_denominator // denom)

        # Reduce the fraction to its simplest form
        common_gcd = gcd(numerator, LCM_denominator)
        numerator //= common_gcd
        LCM_denominator //= common_gcd

        return f"{numerator}/{LCM_denominator}"

Explanation:

  • We extract fractions by splitting the expression based on ‘+’ and ‘-’.
  • We calculate the LCM of the denominators to get a common denominator.
  • We adjust each numerator to match the common denominator and sum them.
  • Finally, we reduce the fraction to its simplest form by dividing both numerator and denominator by their greatest common divisor.