592. Fraction Addition and Subtraction
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method: Simulation with Step-by-Step Calculation
This problem asks us to compute the sum of fractions given in a string expression. The input string contains fractions separated by + or -. We need to parse these fractions, perform the addition/subtraction, and return the result as a simplified, irreducible fraction in the format "numerator/denominator".
Solution
Fraction Addition and Subtraction in Python
import math
class Solution:
def fractionAddition(self, expression: str) -> str:
# Python's integers handle arbitrary size, so no overflow issues.
sum_num, sum_den = 0, 1
i = 0
n = len(expression)
while i < n:
# Parse the numerator, including its sign.
start = i
# Move past the sign if it exists.
if expression[i] in ['+', '-']:
i += 1
# Move past the digits of the numerator.
while i < n and expression[i].isdigit():
i += 1
num = int(expression[start:i])
# Skip the '/' delimiter.
i += 1
# Parse the denominator.
start = i
while i < n and expression[i].isdigit():
i += 1
den = int(expression[start:i])
# Add the parsed fraction (num/den) to the current sum (sum_num/sum_den).
# The formula for A/B + C/D is (A*D + B*C) / (B*D).
sum_num = sum_num * den + num * sum_den
sum_den = sum_den * den
# If sum_num is 0, the result is simply 0/1.
if sum_num == 0:
return "0/1"
# Simplify the resulting fraction by dividing by the greatest common divisor (GCD).
common_divisor = math.gcd(abs(sum_num), sum_den)
sum_num //= common_divisor
sum_den //= common_divisor
# Format the output string.
return str(sum_num) + "/" + str(sum_den)
Fraction Addition and Subtraction in Java
class Solution {
// Helper function to compute GCD using the Euclidean algorithm.
private long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public String fractionAddition(String expression) {
// Use long to avoid overflow during intermediate calculations.
long sum_num = 0, sum_den = 1;
int i = 0;
int n = expression.length();
while (i < n) {
// Parse the numerator, including its sign.
int start = i;
// Move past the sign if it exists.
if (expression.charAt(i) == '+' || expression.charAt(i) == '-') {
i++;
}
// Move past the digits of the numerator.
while (i < n && Character.isDigit(expression.charAt(i))) {
i++;
}
long num = Long.parseLong(expression.substring(start, i));
// Skip the '/' delimiter.
i++;
// Parse the denominator.
start = i;
while (i < n && Character.isDigit(expression.charAt(i))) {
i++;
}
long den = Long.parseLong(expression.substring(start, i));
// Add the parsed fraction (num/den) to the current sum (sum_num/sum_den).
// The formula for A/B + C/D is (A*D + B*C) / (B*D).
sum_num = sum_num * den + num * sum_den;
sum_den = sum_den * den;
}
// If sum_num is 0, the result is simply 0/1.
if (sum_num == 0) {
return "0/1";
}
// Simplify the resulting fraction by dividing by the greatest common divisor (GCD).
long common_divisor = gcd(Math.abs(sum_num), sum_den);
sum_num /= common_divisor;
sum_den /= common_divisor;
// Format the output string.
return sum_num + "/" + sum_den;
}
}
Fraction Addition and Subtraction in C++
class Solution {
public:
string fractionAddition(string expression) {
// Use long long to avoid overflow during intermediate calculations.
long long sum_num = 0, sum_den = 1;
int i = 0;
int n = expression.length();
while (i < n) {
// Parse the numerator, including its sign.
int start = i;
// Move past the sign if it exists.
if (expression[i] == '+' || expression[i] == '-') {
i++;
}
// Move past the digits of the numerator.
while (i < n && isdigit(expression[i])) {
i++;
}
long long num = stoll(expression.substr(start, i - start));
// Skip the '/' delimiter.
i++;
// Parse the denominator.
start = i;
while (i < n && isdigit(expression[i])) {
i++;
}
long long den = stoll(expression.substr(start, i - start));
// Add the parsed fraction (num/den) to the current sum (sum_num/sum_den).
// The formula for A/B + C/D is (A*D + B*C) / (B*D).
sum_num = sum_num * den + num * sum_den;
sum_den = sum_den * den;
}
// If sum_num is 0, the result is simply 0/1.
if (sum_num == 0) {
return "0/1";
}
// Simplify the resulting fraction by dividing by the greatest common divisor (GCD).
// std::gcd is available in C++17. For older standards, a manual implementation is needed.
long long common_divisor = std::gcd(std::abs(sum_num), sum_den);
sum_num /= common_divisor;
sum_den /= common_divisor;
// Format the output string.
return to_string(sum_num) + "/" + to_string(sum_den);
}
};
Fraction Addition and Subtraction in TypeScript
/**
* Helper function to compute GCD using the Euclidean algorithm.
* @param a - First number (must be non-negative).
* @param b - Second number (must be non-negative).
* @returns The greatest common divisor of a and b.
*/
function gcd(a: number, b: number): number {
return b === 0 ? a : gcd(b, a % b);
}
function fractionAddition(expression: string): string {
// JS numbers are 64-bit floats (Number type), which can safely represent integers up to 2^53.
// The max denominator product is 10^10, which is smaller than 2^53, so we are safe.
let sum_num: number = 0;
let sum_den: number = 1;
let i = 0;
const n = expression.length;
while (i < n) {
// Parse the numerator, including its sign.
let start = i;
// Move past the sign if it exists.
if (expression[i] === '+' || expression[i] === '-') {
i++;
}
// Move past the digits of the numerator.
while (i < n && expression[i] >= '0' && expression[i] <= '9') {
i++;
}
const num = parseInt(expression.substring(start, i));
// Skip the '/' delimiter.
i++;
// Parse the denominator.
start = i;
while (i < n && expression[i] >= '0' && expression[i] <= '9') {
i++;
}
const den = parseInt(expression.substring(start, i));
// Add the parsed fraction (num/den) to the current sum (sum_num/sum_den).
// The formula for A/B + C/D is (A*D + B*C) / (B*D).
sum_num = sum_num * den + num * sum_den;
sum_den = sum_den * den;
}
// If sum_num is 0, the result is simply 0/1.
if (sum_num === 0) {
return "0/1";
}
// Simplify the resulting fraction by dividing by the greatest common divisor (GCD).
const common_divisor = gcd(Math.abs(sum_num), sum_den);
sum_num /= common_divisor;
sum_den /= common_divisor;
// Format the output string.
return `${sum_num}/${sum_den}`;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.