The Fraction Addition and Subtraction interview question requires you to evaluate a string representing an expression of fraction additions and subtractions. You must return the result as an irreducible fraction in string format. The input might look like "-1/2+1/2" or "1/3-1/2". If the result is an integer, it should still be formatted as a fraction with a denominator of 1 (e.g., "3/1").
Companies like Goldman Sachs, Meta, and Amazon ask the Fraction Addition and Subtraction coding problem to assess a candidate's string parsing abilities and fundamental mathematical knowledge. It tests if you know how to extract numbers from a string, handle signs, find the Least Common Multiple (LCM) or Greatest Common Divisor (GCD) to add fractions, and then simplify the final result.
This problem relies on a String Parsing and Math Simulation pattern.
current_numerator and current_denominator (initially 0/1).num/den, the new numerator is current_numerator * den + num * current_denominator, and the new denominator is current_denominator * den.Expression: "1/3-1/2"
0/1."1/3": num = 1, den = 3.
0*3 + 1*1 = 1. New den: 1*3 = 3.1/3."-1/2": num = -1, den = 2.
1*2 + (-1)*3 = 2 - 3 = -1.3*2 = 6.-1/6.
Final result: "-1/6".1/-6 instead of -1/6).Practice implementing Euclid's algorithm for GCD (def gcd(a, b): return a if b == 0 else gcd(b, a % b)). Also, learn how to use string splitting with multiple delimiters or regex to easily extract signed integers from a mixed string.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Complex Number Multiplication | Medium | Solve | |
| Robot Bounded In Circle | Medium | Solve | |
| Solve the Equation | Medium | Solve | |
| Multiply Strings | Medium | Solve | |
| Add Strings | Easy | Solve |