✅94.21%🔥Easy Solution🔥With Explanation🔥
Intuition \u2712\uFE0F\n#### When we see the problem, the goal is to add and subtract fractions represented as a string expression. Since fractions have differe
# Intuition \u2712\uFE0F\n#### When we see the problem, the goal is to add and subtract fractions represented as a string expression. Since fractions have different denominators, we\'ll need to manage this by finding a common denominator when adding or subtracting them. We also need to simplify the result to ensure it\'s in its irreducible form.\n\n---\n# Approach \uD83D\uDE80\n#### *`Extract the Fractions`*: First, we extract all the numerators and denominators from the string using regular expressions. This helps in breaking down the problem into smaller, manageable pieces.\n#### *`Initialize the Result`*: Start with a fraction represented by a numerator of 0 and a denominator of 1, which effectively means 0/1.\n#### *`Add/Subtract Fractions`*: Iterate over the extracted numerators and denominators, adding each fraction to the result using cross multiplication to handle the different denominators. This step effectively reduces multiple fraction operations to basic arithmetic.\n#### *`Simplify the Result`*: After computing the final fraction, simplify it by dividing the numerator and denominator by their greatest common divisor (GCD).\n#### *`Return the Fraction`*: Finally, return the result in the form of "numerator/denominator".\n\n\n---\n\n\n\n- # Time complexity:\n#### The time complexity is $$O(n)$$, where $$n$$ is the length of the input string. This is because we are processing each character of the input string to extract numerators and denominators and then performing a fixed amount of work for each fraction.\n\n\n- # Space complexity:\n#### The space complexity is $$O(1)$$, excluding the input and output, since we\'re only using a fixed amount of extra space for the numerator, denominator, and a few variables for calculations. The space used by the regular expression for extracting numbers is proportional to the number of fractions but remains constant with respect to the length of the input.\n---\n\n# Code\n```python []\nclass Solution:\n    def fractionAddition(self, expression: str) -> str:\n        nums = list(map(int, re.findall(r\'[+-]?\\d+\', expression)))\n        numerator = 0\n        denominator = 1\n        \n        for i in range(0, len(nums), 2):\n            num, den = nums[i], nums[i + 1]\n            numerator = numerator * den + num * denominator\n            denominator *= den\n        \n        common_divisor = gcd(numerator, denominator)\n        return f"{numerator // common_divisor}/{denominator // common_divisor}"\n```\n```C++ []\n#include <string>\n#include <vector>\nclass Solution {\npublic:\n    string fractionAddition(string expression) {\n        int numerator = 0, denominator = 1;\n        int i = 0, n = expression.size();\n\n        while (i < n) {\n            int sign = 1;\n            if (expression[i] == \'+\' || expression[i] == \'-\') {\n                if (expression[i] == \'-\') sign = -1;\n                i++;\n            }\n\n            int num = 0;\n            while (i < n && isdigit(expression[i])) {\n                num = num * 10 + (expression[i] - \'0\');\n                i++;\n            }\n            num *= sign;\n\n            i++;\n\n            int den = 0;\n            while (i < n && isdigit(expression[i])) {\n                den = den * 10 + (expression[i] - \'0\');\n                i++;\n            }\n\n            numerator = numerator * den + num * denominator;\n            denominator *= den;\n\n            int gcdVal = gcd(abs(numerator), denominator);\n            numerator /= gcdVal;\n            denominator /= gcdVal;\n        }\n\n        return to_string(numerator) + "/" + to_string(denominator);\n    }\n};\n\n```\n```javascript []\nvar fractionAddition = function(expression) {\n    let numerator = 0, denominator = 1;\n\n    const regex = /([+-]?\\d+)\\/(\\d+)/g;\n    let match;\n\n    while ((match = regex.exec(expression)) !== null) {\n        let num = parseInt(match[1]);\n        let den = parseInt(match[2]);\n\n        numerator = numerator * den + num * denominator;\n        denominator *= den;\n\n        let gcdVal = gcd(Math.abs(numerator), denominator);\n        numerator /= gcdVal;\n        denominator /= gcdVal;\n    }\n\n    return numerator + "/" + denominator;\n};\n\nfunction gcd(a, b) {\n    while (b !== 0) {\n        let temp = b;\n        b = a % b;\n        a = temp;\n    }\n    return a;\n}\n\n```\n```java []\nclass Solution {\n    public String fractionAddition(String expression) {\n        int numerator = 0, denominator = 1;\n        \n        Pattern pattern = Pattern.compile("([+-]?\\\\d+)/(\\\\d+)");\n        Matcher matcher = pattern.matcher(expression);\n        \n        while (matcher.find()) {\n            int num = Integer.parseInt(matcher.group(1));\n            int den = Integer.parseInt(matcher.group(2));\n            \n            numerator = numerator * den + num * denominator;\n            denominator *= den;\n            \n            int gcdVal = gcd(Math.abs(numerator), denominator);\n            numerator /= gcdVal;\n            denominator /= gcdVal;\n        }\n        \n        return numerator + "/" + denominator;\n    }\n    \n    private int gcd(int a, int b) {\n        while (b != 0) {\n            int temp = b;\n            b = a % b;\n            a = temp;\n        }\n        return a;\n    }\n}\n\n```\n```C# []\npublic class Solution {\n    public string FractionAddition(string expression) {\n        int numerator = 0, denominator = 1;\n\n        Regex regex = new Regex(@"([+-]?\\d+)\\/(\\d+)");\n        MatchCollection matches = regex.Matches(expression);\n\n        foreach (Match match in matches) {\n            int num = int.Parse(match.Groups[1].Value);\n            int den = int.Parse(match.Groups[2].Value);\n\n            numerator = numerator * den + num * denominator;\n            denominator *= den;\n\n            int gcdVal = GCD(Math.Abs(numerator), denominator);\n            numerator /= gcdVal;\n            denominator /= gcdVal;\n        }\n\n        return $"{numerator}/{denominator}";\n    }\n\n    private int GCD(int a, int b) {\n        while (b != 0) {\n            int temp = b;\n            b = a % b;\n            a = temp;\n        }\n        return a;\n    }\n}\n\n```\n---\n\n![Screenshot 2023-08-20 065922.png](https://assets.leetcode.com/users/images/cabb99f0-5b1d-465b-8c32-7d427d5c2bdc_1724374731.076821.png)\n\n
['Math', 'String', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']