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 Single Pass with Running Sum Approach INPUT Expression String: "-1/2+1/2+1/3" Parsed Fractions: -1 2 +1 2 +1 3 Initial Running Sum: 0 1 num = 0, den = 1 ALGORITHM STEPS 1 Add -1/2 to 0/1 (-1*1 + 0*2)/(2*1) = -1/2 -1/2 2 Add +1/2 to -1/2 (1*2 + (-1)*2)/(2*2) = 0/4 0/4 3 Add +1/3 to 0/4 (1*4 + 0*3)/(3*4) = 4/12 4/12 4 Reduce by GCD GCD(4,12) = 4 4/12 = (4/4)/(12/4) = 1/3 Formula: a/b + c/d new_num = a*d + c*b new_den = b*d FINAL RESULT 1 3 Output String: "1/3" Verification: -1/2 + 1/2 + 1/3 = 0 + 1/3 = 1/3 OK - Irreducible! Key Insight: Use a running sum approach: start with 0/1, then add each parsed fraction using the formula (a*d + c*b)/(b*d). After processing all fractions, reduce the result by dividing both numerator and denominator by their GCD to get the irreducible fraction. TutorialsPoint - Fraction Addition and Subtraction | Single Pass with Running Sum
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