1012. Equal Rational Numbers
My accepted Python solution to LeetCode problem 1012, Equal Rational Numbers, running in 0ms.
- Difficulty: Hard
- Python
- Runtime 0ms
- Memory 17.4MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 0ms, memory 17.4MB, accepted 2026-01-01.
class Solution:
def isRationalEqual(self, s: str, t: str) -> bool:
from fractions import Fraction
def parse(s):
if '(' not in s:
return Fraction(s).limit_denominator()
# Split into integer.non_repeating(repeating)
idx_paren = s.index('(')
idx_dot = s.index('.') if '.' in s else len(s)
integer = s[:idx_dot]
non_repeat = s[idx_dot+1:idx_paren]
repeat = s[idx_paren+1:-1]
# Convert to fraction
# x = integer.non_repeat + 0.000...repeat_repeat_repeat...
# Let y = 0.non_repeat_repeat_repeat_repeat...
# y * 10^len(non_repeat) = non_repeat.repeat_repeat_repeat...
# y * 10^len(non_repeat) * 10^len(repeat) = non_repeat_repeat.repeat_repeat...
# y * 10^(a+b) - y * 10^a = non_repeat_repeat - non_repeat (where a=len(non_repeat), b=len(repeat))
a, b = len(non_repeat), len(repeat)
if b == 0:
return Fraction(s[:idx_paren]).limit_denominator()
# (10^(a+b) - 10^a) * y = int(non_repeat + repeat) - int(non_repeat or 0)
nr = int(non_repeat) if non_repeat else 0
nrr = int(non_repeat + repeat) if non_repeat else int(repeat)
numerator = nrr - nr
denominator = (10 ** (a + b)) - (10 ** a)
return Fraction(int(integer), 1) + Fraction(numerator, denominator)
return abs(float(parse(s)) - float(parse(t))) < 1e-9