You are given a string expression made of fractions joined by + and -, such as 2/5-1/3+4/1. Work out its value and return it as a string "p/q".
The answer must be in lowest terms, with the sign (if any) on the numerator. A whole number is written over 1, so 3 is "3/1" and zero is "0/1".
Example 1
Input: expression = "1/4-5/6+2/3" Output: "1/12" Why: 3/12 − 10/12 + 8/12 = 1/12
2 more examples and the constraints
Example 2
Input: expression = "-3/7+3/7" Output: "0/1" Why: the two cancel; zero is written 0/1
Example 3
Input: expression = "5/2+3/2" Output: "4/1" Why: 8/2 is the whole number 4
Constraints
- 1 ≤ number of fractions ≤ 10
- Each fraction is already in lowest terms, with numerator and denominator between 1 and 10
- Only the first fraction may have no sign in front of it
- The answer fits in a 32-bit integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- One common denominatorO(n)
- Running sum with gcdO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10 fractions | Verdict |
|---|---|---|---|
| One common denominator | O(n) | Short; relies on denominators ≤ 10 | |
| Running sum with gcd | O(n) | Best; works for any denominators |
n = length of the expression. Both do one pass; the running sum calls gcd once per fraction.
Edge cases to test
- The sum is zero. "-3/7+3/7" must give "0/1", not "0/49".
- A whole-number answer. "5/2+3/2" gives "4/1": keep the /1.
- A negative answer. The minus sign goes on the numerator: "-1/10".
- Two-digit numbers. "10/1" and "1/10": read every digit, not just one.
- A single fraction. "7/1" comes back unchanged.
Common mistakes
- Reading only one digit per number, which breaks on 10.
- Passing a negative numerator to gcd, which can return a negative divisor and flip the signs.
- Returning "4" or "0" instead of "4/1" or "0/1".
How to talk through it
- 1Clarify. How is a whole number written? Where does the minus sign go? How big can the numbers get?
- 2Plan the parse. Each fraction is an optional sign, digits, a slash, digits. The sign stays with the numerator.
- 3Add fractions. Cross-multiply into a running num/den, then reduce by the gcd every step.
- 4Mention the shortcut. With denominators up to 10, everything fits over 2520, but the running sum is more general.
- 5Test out loud. Run a sum that cancels to zero and one that is a whole number before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?