Skip to main content

Fraction Addition and Subtraction - Solution & Explanation

MediumMathStringSimulation17 min readAsked at: Meta, Google, Ixl +2
Practice this problem

Problem Statement

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.

 

Example 1:

Input: expression = "-1/2+1/2"
Output: "0/1"

Example 2:

Input: expression = "-1/2+1/2+1/3"
Output: "1/3"

Example 3:

Input: expression = "1/3-1/2"
Output: "-1/6"

 

Constraints:

  • The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
  • Each fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
  • The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
  • The number of given fractions will be in the range [1, 10].
  • The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.

Approach Overview

Problem Overview: You receive a string representing addition and subtraction of fractions such as "-1/2+1/2+1/3". Each fraction has a numerator and denominator, and the final answer must be returned as an irreducible fraction. The challenge is parsing the string, combining fractions correctly, and simplifying the result using math operations like GCD or LCM.

Approach 1: Using LCM for Common Denominator (O(n) time, O(1) space)

Parse each fraction from the string and maintain a running numerator and denominator for the result. When a new fraction appears, compute the LCM of the current denominator and the new fraction’s denominator so both fractions share a common base. Convert both numerators to that denominator, perform the addition or subtraction, and update the result fraction. After each operation, simplify the fraction by dividing numerator and denominator by their gcd. The algorithm scans the string once while performing constant-time arithmetic per fraction, giving O(n) time complexity and O(1) extra space. This approach directly models real fraction arithmetic and is easy to reason about.

Approach 2: Consecutive Fraction Handling (O(n) time, O(1) space)

Instead of computing LCM every time, maintain a running fraction result_num/result_den. As you iterate through the expression, parse the sign, numerator, and denominator of the next fraction. Combine it with the running result using the formula:

result_num = result_num * den + sign * num * result_den

result_den = result_den * den

After each update, reduce the fraction using gcd(result_num, result_den). This effectively simulates consecutive fraction operations, which fits naturally with a single pass over the input. Parsing the expression is the main work, so the overall complexity remains O(n) time with O(1) space. The logic relies heavily on integer arithmetic and careful simulation of fraction evaluation.

Recommended for interviews: Consecutive Fraction Handling is usually the preferred solution. It keeps the implementation compact and avoids explicit LCM calculations while still producing simplified results. Interviewers typically look for correct fraction arithmetic, careful parsing of signs and denominators, and consistent fraction reduction with GCD. The LCM-based method is still valuable because it mirrors how fractions are taught mathematically, demonstrating strong fundamentals before optimizing the implementation.

Approach 1: Using LCM for Common Denominator

This approach involves using the Least Common Multiple (LCM) to find a common denominator for all fractions. Then, add or subtract the numerators accordingly, and finally, simplify the resulting fraction.

We loop through each fraction in the expression, calculate the LCM of the current denominator and the one in the expression, adjust numerators accordingly, and perform the addition or subtraction. Finally, the result is simplified by dividing it by the GCD of the numerator and denominator.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of the expression.
Space Complexity: O(1), as we only use a fixed amount of additional space for variables.

Try this approach in the editor →

Approach 2: Consecutive Fraction Handling

In this method, we handle each fraction consecutively, updating the numerator and denominator dynamically. This maintains an accumulated result for fractions encountered sequentially.

This solution parses through the expression while employing a dynamic running total, adjusting numerically with current fractions, computing the least common multiple in simultaneous manner.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) with direct proportionality to length.
Space Complexity: O(1) as with minimum additional memory usage constant.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

Go

JavaScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Using LCM for Common Denominator

Time Complexity: O(n), where n is the length of the expression.
Space Complexity: O(1), as we only use a fixed amount of additional space for variables.

Consecutive Fraction Handling

Time Complexity: O(n) with direct proportionality to length.
Space Complexity: O(1) as with minimum additional memory usage constant.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Using LCM for Common DenominatorO(n)O(1)When you want clear mathematical steps that mirror manual fraction addition
Consecutive Fraction HandlingO(n)O(1)General interview solution with compact implementation and single-pass parsing

Video Solution

Fraction Addition and Subtraction | Simple Simulation | Leetcode 592 | codestorywithMIK • codestorywithMIK • 13,079 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Fraction Addition and Subtraction easy or hard?
This problem is rated Medium because it mixes string parsing with fraction arithmetic. The logic itself is straightforward, but careful handling of signs, denominators, and fraction reduction is required to avoid mistakes.
Fraction Addition and Subtraction Python/Java solution
Both Python and Java implementations follow the same idea: parse each fraction, combine it with the running result using cross multiplication, and reduce using the gcd function. The logic stays O(n) with constant extra space.
How to solve Fraction Addition and Subtraction in O(n)?
Parse the expression from left to right and keep a running fraction result_num/result_den. For each new fraction, update the result using cross multiplication, then simplify using gcd(result_num, result_den). Since each character is processed once, the algorithm runs in O(n) time.
What is the best approach for Fraction Addition and Subtraction?
The most practical approach is consecutive fraction handling. Maintain a running numerator and denominator, combine each new fraction using cross multiplication, and reduce the result with GCD. This method processes the expression in one pass with O(n) time and O(1) space.
Is Fraction Addition and Subtraction asked at Google/Amazon/Meta?
Fraction manipulation and expression parsing problems appear in interviews at companies like Amazon and Google. They typically test string parsing, mathematical reasoning, and careful handling of integer arithmetic.
What data structure is used in Fraction Addition and Subtraction?
No complex data structure is required. The solution mainly uses integer variables to track numerators and denominators while scanning the string. The core techniques come from math operations and string parsing.
What is the time complexity of Fraction Addition and Subtraction?
The standard solutions run in O(n) time where n is the length of the input string. Each fraction is parsed once and combined using constant-time arithmetic operations and a GCD calculation.

Ready to solve this problem?

Practice Fraction Addition and Subtraction with our built-in code editor and test cases.

Practice on FleetCode