#592

Fraction Addition and Subtraction

Medium
MathStringSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution efficiently processes the expression in a single pass, directly calculating the total numerator and denominator without needing to repeatedly find a common denominator. This reduces unnecessary computations and speeds up the process.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize total numerator and denominator to 0 and 1 respectively.
  2. 2Step 2: Split the expression into fractions using regex to capture signs and numerators/denominators.
  3. 3Step 3: For each fraction, update the total numerator and denominator using the formula for adding fractions.
  4. 4Step 4: After processing all fractions, simplify the result using the GCD.
  5. 5Step 5: Format the result as a string in the form 'numerator/denominator'.
solution.py20 lines
1from math import gcd
2
3def fractionAddition(expression):
4    total_num = 0
5    total_denom = 1
6    fractions = expression.split(' ')
7    for frac in fractions:
8        sign = 1
9        if frac[0] == '-':
10            sign = -1
11            frac = frac[1:]
12        elif frac[0] == '+':
13            frac = frac[1:]
14        num, denom = map(int, frac.split('/'))
15        total_num = total_num * denom + sign * num * total_denom
16        total_denom *= denom
17    if total_num == 0:
18        return '0/1'
19    divisor = gcd(total_num, total_denom)
20    return f'{total_num // divisor}/{total_denom // divisor}'

Complexity note: The time complexity is O(n) because we only traverse the string once to extract fractions and compute the result, making it efficient.

  • 1Understanding how to handle fractions is crucial in many mathematical problems.
  • 2Simplifying fractions using GCD is a common technique.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.