Python 0592.py
class Solution:
def fractionAddition(self, expression: str) -> str:
n = [] # numerators
d = [] # denominators
sign = +1 # if no sign then plus
value = 0 # current number, parse digit by digit
# extract all numbers, incl. sign
for c in expression + "+": # add dummy char to fetch the last number without hassle
if c in "0123456789": # another digit
value *= 10
value += int(c)
else:
# not a digit, therefore store the
if value > 0: # value is only zero if input starts with "-"
# split into numerator and denominator
value *= sign
if len(n) == len(d):
n.append(value)
else:
d.append(value)
# reset
value = 0
sign = +1
# could by a sign
if c == "+":
sign = +1
elif c == "-":
sign = -1
# or "/", nothing to do in that case
# product of all denominators
full_d = reduce(mul, d)
# convert each numerator such that it belongs to that "unified" denominator
full_n = 0
for nn, dd in zip(n, d):
full_n += nn * full_d // dd
# edge case
if full_n == 0:
return "0/1"
# make it irreducible, divide by greatest common divisor
shared = gcd(full_n, full_d)
full_n //= shared
full_d //= shared
return f"{full_n}/{full_d}"
Difficulty
and has an acceptance rate of about 67% (200k+ submissions).
Typical patterns to solve this problem:
- Math
- Simulation
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided fractionAddition method receives a string that represents a sequence of fractional terms combined with ‘+’ and ‘-’ operators. Its purpose is to evaluate the expression and return the result as a reduced fraction in the form “numerator/denominator”. The implementation follows a linear scan to extract signed numerators and denominators, computes a common denominator, aggregates the adjusted numerators, and finally reduces the result using the greatest common divisor.
Parsing the Input
The core of the parsing logic is a single loop that walks through each character of the input string, with an extra ‘+’ appended to simplify handling of the final number. A running variable value accumulates digit characters, while sign records the sign that precedes the current number. When a non-digit character is encountered, the accumulated value (if non-zero) is stored, and the sign is updated according to the character.
sign = +1
value = 0
for c in expression + "+": # dummy '+' forces processing of the last term
if c in "0123456789": # digit continues the current number
value *= 10
value += int(c)
else:
if value > 0: # a complete number has been read
value *= sign
if len(n) == len(d):
n.append(value) # first number of a pair → numerator
else:
d.append(value) # second number of a pair → denominator
value = 0
sign = +1
if c == "+":
sign = +1
elif c == "-":
sign = -1
# '/' is ignored; it merely separates numerator and denominator
The loop guarantees that every numeric token, together with its sign, is captured exactly once. The appended ‘+’ eliminates the need for a separate finalization step after the loop.
Storing Numerators and Denominators
Two parallel lists, n for numerators and d for denominators, are populated during parsing. The decision of whether the current number belongs to n or d is based on the relative lengths of the two lists: when they are equal, the next number is a numerator; otherwise it is a denominator. This parity check ensures that each fraction contributes one numerator followed by one denominator, preserving the original order of the expression.
Computing a Common Denominator
After parsing, the algorithm computes the product of all denominators to obtain a common denominator that can accommodate every term without loss of precision. The reduce function together with operator.mul performs this multiplication in a single pass over the denominator list.
full_d = reduce(mul, d) # product of all denominators
Using the product rather than a least common multiple is acceptable because the subsequent reduction step eliminates any unnecessary factors, and it avoids the overhead of computing an LCM.
Converting to the Common Denominator
With a unified denominator in hand, each fraction’s numerator is scaled appropriately and summed into full_n. The scaling factor for a particular fraction is the integer division of the common denominator by that fraction’s original denominator, guaranteeing exact arithmetic.
full_n = 0
for nn, dd in zip(n, d):
full_n += nn * full_d // dd
The use of integer division (//) ensures that the intermediate results remain integers, eliminating any floating-point rounding concerns.
Handling the Zero Result Edge Case
If the aggregated numerator full_n evaluates to zero, the method returns the canonical representation of zero as “0/1”. This explicit check prevents a division by zero when the greatest common divisor is later computed.
if full_n == 0:
return "0/1"
Reducing to Irreducible Form
The final step reduces the fraction to its simplest form by dividing both numerator and denominator by their greatest common divisor. The gcd function from the math module provides an efficient Euclidean algorithm implementation.
shared = gcd(full_n, full_d)
full_n //= shared
full_d //= shared
return f"{full_n}/{full_d}"
Because both full_n and full_d are guaranteed to be non-negative after the earlier sign handling, the reduction yields a properly signed numerator and a positive denominator.
Performance Optimizations
The implementation exhibits several deliberate performance choices. The parsing loop processes the input string exactly once, achieving linear time with respect to the length of the expression. Accumulating digits into an integer (value) avoids the overhead of string slicing or conversion for each token. The parity-based list insertion eliminates the need for a more complex data structure to pair numerators with denominators.
Computing the common denominator as a product sidesteps the computational cost of repeatedly calculating least common multiples, while the final gcd reduction removes any superfluous factors introduced by that product. All arithmetic operations remain within the integer domain, leveraging Python’s arbitrary-precision integers without incurring the cost of floating-point conversions.
By consolidating the scaling and summation of numerators into a single loop, the code minimizes the number of passes over the data. The early exit for a zero numerator prevents unnecessary gcd computation in that scenario. Overall, the algorithm balances simplicity with efficient use of built-in operations to deliver fast evaluation of fractional addition expressions.
ELI5 - Simplified Explanation
Imagine a busy box where tiny toy parts are scattered everywhere. This code acts like a very precise helper that organizes all these pieces into neat piles. First, the code walks along a long string of numbers, just like reading a storybook, to find every single numerator and denominator hiding inside. When it spots a number, it keeps track of whether that number is positive or negative by looking for the plus or minus signs. After collecting all the top and bottom parts of the fractions, the helper makes sure they all talk the same language by giving them a common bottom number, which is like finding a common size for building blocks. Once everything is on the same level, the code adds all those top numbers together to find the final total. Finally, to keep everything tidy, the helper looks for a way to shrink the result down to its smallest, simplest size by dividing the top and bottom by the biggest possible secret match they share. After all that careful sorting and cleaning, the final pieces sit perfectly in a fraction ready to be shown to the world.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | JS | Java | Go | Python | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | Go, Java, JavaScript, Python | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 640: Solve the Equation
Solved On The Same Day
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality