Fraction Addition and Subtraction - Problem

You're given a string expression that represents a series of fraction additions and subtractions. Your task is to evaluate this mathematical expression and return the result as a simplified fraction in string format.

The input string contains fractions in the format numerator/denominator, separated by + or - operators. For example: "-1/2+1/2" or "-1/2+1/2+1/3".

Key Requirements:

  • The final result must be an irreducible fraction (simplified to lowest terms)
  • If the result is a whole number, format it as "number/1" (e.g., "2/1")
  • Handle negative fractions correctly
  • The expression will always be valid

This problem tests your understanding of fraction arithmetic, greatest common divisor (GCD), and string parsing.

Input & Output

example_1.py — Basic Addition
$ Input: "-1/2+1/2"
Output: "0/1"
💡 Note: The fractions -1/2 and 1/2 cancel each other out, resulting in 0. Since 0 is an integer, we format it as 0/1.
example_2.py — Mixed Operations
$ Input: "-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 simplest form.
example_3.py — Simplification Required
$ Input: "1/3-1/2"
Output: "-1/6"
💡 Note: Find common denominator: 1/3 - 1/2 = 2/6 - 3/6 = -1/6. The result is already simplified.

Constraints

  • The input string only contains '0' to '9', '/', '+' and '-'
  • The input starts and ends with a number
  • Each fraction is in the format ±numerator/denominator
  • Cross-multiplication will not cause overflow for valid inputs
  • All given inputs are valid fraction expressions

Visualization

Tap to expand
Fraction Addition Algorithm FlowInput String:"1/3-1/2+1/6"Parse into fractionsInitialize:Result = 0/1Running totalStep 1:0/1 + 1/3= 1/3GCD(1,3)=1Step 2:1/3 + (-1/2)= -1/6GCD(1,6)=1Step 3:-1/6 + 1/6= 0/1GCD(0,1)=1Key Formula:(a/b) + (c/d)= (a×d + b×c)(b×d)Then simplify with GCDFinal Result:"0/1"Irreducible fraction
Understanding the Visualization
1
Parse Expression
Break down the string into individual fractions with their signs
2
Initialize Result
Start with 0/1 as our running total
3
Add Each Fraction
Use cross-multiplication: (a/b) + (c/d) = (a×d + b×c)/(b×d)
4
Simplify Immediately
Use GCD to reduce the fraction to lowest terms after each operation
5
Return Result
Format as string with numerator/denominator
Key Takeaway
🎯 Key Insight: By maintaining a running sum and simplifying immediately after each operation using GCD, we prevent integer overflow while keeping the algorithm simple and efficient. This approach mirrors how you'd manually solve fraction arithmetic step by step.
Asked in
Google 12 Amazon 8 Microsoft 6 Apple 4
28.5K Views
Medium Frequency
~15 min Avg. Time
782 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