592. Fraction Addition and Subtraction LeetCode Solution

In this guide, you will get 592. Fraction Addition and Subtraction LeetCode Solution with the best time and space complexity. The solution to Fraction Addition and Subtraction problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Fraction Addition and Subtraction solution in C++
  4. Fraction Addition and Subtraction solution in Java
  5. Fraction Addition and Subtraction solution in Python
  6. Additional Resources
592. Fraction Addition and SubtractionLeetCode Solution image

Problem Statement of Fraction Addition and Subtraction

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.

Example 1:

Input: expression = “-1/2+1/2”
Output: “0/1”

Example 2:

Input: expression = “-1/2+1/2+1/3”
Output: “1/3”

Example 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.

See also  229. Majority Element II LeetCode Solution

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

592. Fraction Addition and Subtraction LeetCode Solution in C++

class Solution {
 public:
  string fractionAddition(string expression) {
    istringstream iss(expression);
    char _;
    int a;
    int b;
    int A = 0;
    int B = 1;

    // Init: A / B = 0 / 1
    // A / B + a / b = (Ab + aB) / Bb
    // So, in each round, set A = Ab + aB, B = Bb.
    while (iss >> a >> _ >> b) {
      A = A * b + a * B;
      B *= b;
      const int g = abs(__gcd(A, B));
      A /= g;
      B /= g;
    }

    return to_string(A) + "/" + to_string(B);
  }
};
/* code provided by PROGIEZ */

592. Fraction Addition and Subtraction LeetCode Solution in Java

class Solution {
  public String fractionAddition(String expression) {
    Scanner sc = new Scanner(expression).useDelimiter("/|(?=[+-])");
    int A = 0;
    int B = 1;

    // Init: A / B = 0 / 1
    // A / B + a / b = (Ab + aB) / Bb
    // So, in each round, set A = Ab + aB, B = Bb.
    while (sc.hasNext()) {
      final int a = sc.nextInt();
      final int b = sc.nextInt();
      A = A * b + a * B;
      B *= b;
      final int g = gcd(A, B);
      A /= g;
      B /= g;
    }

    return A + "/" + B;
  }

  private int gcd(int a, int b) {
    return a == 0 ? Math.abs(b) : gcd(b % a, a);
  }
}
// code provided by PROGIEZ

592. Fraction Addition and Subtraction LeetCode Solution in Python

class Solution:
  def fractionAddition(self, expression: str) -> str:
    ints = list(map(int, re.findall('[+-]?[0-9]+', expression)))
    A = 0
    B = 1

    for a, b in zip(ints[::2], ints[1::2]):
      A = A * b + a * B
      B *= b
      g = math.gcd(A, B)
      A //= g
      B //= g

    return str(A) + '/' + str(B)
 # code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.