Evaluate Fraction Expression

You are given a string expression that represents a sequence of fraction additions and subtractions.

Each fraction is written in the form numerator/denominator, and the expression may contain '+' and '-' operators between fractions.

Return the final result as a string in lowest terms.

A valid result must follow these rules:

  • The result must always be returned in the form p/q.
  • If the result is a whole number, return it as a fraction with denominator 1.
  • For example, 2 should be returned as "2/1".
  • The final fraction must be irreducible.

Notes:

  • The first fraction may be positive or negative.
  • A positive fraction does not include a leading '+'.
  • All input fractions are already in irreducible form.

Example 1:

Input: expression = "2/3+1/6"

Output: "5/6"

Explanation:

  • 2/3 = 4/6
  • 4/6 + 1/6 = 5/6

Example 2:

Input: expression = "5/4-1/2+3/8"

Output: "9/8"

Explanation:

  • 5/4 = 10/8
  • 1/2 = 4/8
  • 10/8 - 4/8 + 3/8 = 9/8

Now Your Turn!

Pick the correct output for the given input

Input: expression = "1/2-1/3+1/4"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= expression.length <= 100
  • expression contains only digits '0' to '9', '/', '+', and '-'
  • The expression contains between 1 and 10 fractions
  • Every fraction is valid and written as numerator/denominator
  • Each input fraction is already in irreducible form
  • 1 <= numerator <= 10
  • 1 <= denominator <= 10
  • The first fraction may be negative, but a positive first fraction will not have a '+' sign
  • The final answer is guaranteed to fit in a 32-bit signed integer range for both numerator and denominator

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
string fractionAddition(string expression) {
// Your code goes here
}
};
Test Case

Input:

Expression