Fraction Addition and Subtraction - 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.

Input & Output

Example 1 — Basic Mixed Operations
$ Input: expression = "-1/2+1/2+1/3"
Output: "1/3"
💡 Note: First: -1/2 + 1/2 = 0, then 0 + 1/3 = 1/3. The result is already in irreducible form.
Example 2 — Multiple Fractions
$ Input: expression = "1/3-1/2"
Output: "-1/6"
💡 Note: To subtract 1/3 - 1/2, we find common denominator: 2/6 - 3/6 = -1/6
Example 3 — Result is Integer
$ Input: expression = "1/2+1/2"
Output: "1/1"
💡 Note: 1/2 + 1/2 = 1, which must be expressed as fraction 1/1

Constraints

  • The input string only contains '0' to '9', '/', '+' and '-'
  • Each fraction is in the form ±numerator/denominator
  • Each numerator and denominator is in the range [1, 10]
  • The final result should be an irreducible fraction

Visualization

Tap to expand
Fraction Addition and Subtraction"-1/2+1/2+1/3"Input ExpressionParse & CalculateCommon DenominatorsProcess"1/3"OutputStep-by-step calculation:-1/2 + 1/2 = 0/10/1 + 1/3 = 1/3GCD(1,3) = 1, so 1/3 is irreducibleResult: 1/3
Understanding the Visualization
1
Input
Expression string with fractions and operators
2
Process
Parse and accumulate fractions using common denominators
3
Output
Irreducible fraction as string
Key Takeaway
🎯 Key Insight: Parse fractions sequentially and use GCD for reduction to get irreducible results
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
956 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen