Python 0166.py
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
# integer
if numerator % denominator == 0:
return str(numerator // denominator)
negative = (numerator * denominator < 0)
numerator = abs(numerator)
denominator = abs(denominator)
# integer part
prefix = str(numerator // denominator) + "."
numerator %= denominator
if negative:
prefix = "-" + prefix
remainders = { }
digits = 0
suffix = ""
while True:
# remainder seen before ?
if numerator in remainders:
begin = remainders[numerator]
repeat = suffix[begin:]
if repeat == "0":
return prefix + suffix[:begin]
suffix = suffix[:begin] + "(" + suffix[begin:] + ")"
return prefix + suffix
remainders[numerator] = digits
# chop off
numerator *= 10
next = str(numerator // denominator)
numerator %= denominator
suffix += next
digits += 1
Difficulty
and has an acceptance rate of about 31% (1+ million submissions).
Typical patterns to solve this problem:
- Hash Table
- Math
- 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 fractionToDecimal method converts a rational number, given by a numerator and a denominator, into its decimal string representation. It produces a finite decimal when the division terminates and encloses the repeating part of an infinite decimal in parentheses. The implementation follows a step-wise approach: it first checks for exact division, determines the sign, extracts the integer part, and then iteratively computes the fractional digits while detecting cycles.
Integer Check
The function begins by handling the simplest case where the division yields no remainder. If the numerator divides evenly by the denominator, the result is an integer and the method returns it directly as a string.
if numerator % denominator == 0:
return str(numerator // denominator)
This early exit avoids any further processing for whole-number results.
Sign Determination
The sign of the final output is derived from the product of the numerator and denominator. A boolean flag records whether the result should be negative. Both operands are then converted to their absolute values so that the subsequent arithmetic can be performed uniformly.
negative = (numerator * denominator < 0)
numerator = abs(numerator)
denominator = abs(denominator)
Integer Part Construction
The integer portion of the quotient is obtained by integer division. It is concatenated with a decimal point to form the initial part of the output string, stored in prefix. If the result is negative, a leading minus sign is added before the integer part.
prefix = str(numerator // denominator) + "."
numerator %= denominator
if negative:
prefix = "-" + prefix
At this stage numerator holds the remainder that will be used to generate the fractional digits.
Remainder Tracking Loop
The core of the algorithm is a loop that produces each fractional digit and simultaneously checks for repetition. A dictionary named remainders maps each observed remainder to the position (digit count) at which it first appeared. Two auxiliary variables, suffix and digits, accumulate the fractional digits and count them, respectively.
remainders = {}
digits = 0
suffix = ""
while True:
if numerator in remainders:
begin = remainders[numerator]
repeat = suffix[begin:]
if repeat == "0":
return prefix + suffix[:begin]
suffix = suffix[:begin] + "(" + suffix[begin:] + ")"
return prefix + suffix
remainders[numerator] = digits
numerator *= 10
next = str(numerator // denominator)
numerator %= denominator
suffix += next
digits += 1
Cycle Detection
When a remainder repeats, the digits from its first occurrence to the current position form the repeating segment. The code extracts this segment (repeat) and checks whether it consists solely of the digit '0'. If the repeating part is a single zero, the method trims the trailing zeros and returns the non-repeating portion, effectively handling cases like 1/2 that produce 0.5 rather than 0.5(0).
Parentheses Insertion
If the repeating segment contains non-zero digits, the method inserts an opening parenthesis at the start of the segment and a closing parenthesis at the end, then returns the concatenated prefix and modified suffix. This yields the canonical representation such as 0.(6) for 2/3.
Digit Generation
When a new remainder is encountered, it is recorded in remainders with the current digit index. The remainder is multiplied by ten, the next digit is obtained by integer division, and the remainder is updated with the modulus operation. The digit is appended to suffix, and the digit counter is incremented.
Edge Cases Handled
The implementation gracefully manages several special situations:
- Exact Division - When the numerator is a multiple of the denominator, the early integer check returns the whole number without a decimal point.
- Zero Numerator - A numerator of zero triggers the exact division branch, yielding
"0"as the result. - Negative Values - The sign flag ensures that any combination of negative numerator and/or denominator produces a correctly prefixed minus sign.
- Repeating Zero Fraction - When the repeating portion consists only of zeros, the code removes the redundant parentheses and trailing zeros, delivering a clean terminating decimal.
- Long Repeating Cycles - By storing each remainder with its position, the algorithm can detect cycles of arbitrary length, guaranteeing correct placement of parentheses for fractions like
1/7.
Performance Optimizations
The method incorporates several techniques that keep the execution efficient:
- Dictionary Lookup for Remainders - Using a hash map to store previously seen remainders provides constant-time detection of cycles, eliminating the need for nested loops or repeated scans of the generated digits.
- Early Termination on Terminating Zero Cycle - The explicit check for a repeating
"0"allows the function to exit immediately without constructing unnecessary parentheses, saving both time and string manipulation overhead. - In-Place String Building - The fractional part is built incrementally by concatenating single-character strings to
suffix. This approach avoids the creation of intermediate large lists or arrays. - Minimal Variable Scope - Variables are introduced only when needed and reused where possible, reducing memory pressure during the iterative process.
Overall, the code follows a clear procedural flow, leveraging Python’s built-in arithmetic and dictionary structures to achieve correct decimal conversion with concise handling of edge conditions and efficient cycle detection.
ELI5 - Simplified Explanation
Imagine you have a big cake and you want to share it with your friends. Sometimes, when you cut the cake, everyone gets a perfectly even piece. This code is like a helper that looks at a math problem to see if the answer is a whole number, like two, or if it has a little bit left over, like a decimal.
If the cake does not divide perfectly, the computer starts making little slices by multiplying the leftover piece by ten over and over again. It keeps track of every new number it finds by writing it down in a special notebook.
The code keeps going until it finds a pattern that repeats itself, just like a song that plays the same notes over and over. When it sees that the same number it has already written down shows up again, it knows the math problem will keep repeating forever. It puts those repeating numbers inside parentheses to show that they are the part that never ends. If the numbers don't repeat in a special way, it just keeps adding pieces until it finds the whole answer.
Code Quality
Complexity Analysis
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++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | C# | Python | Rust | Java | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | aylei | Rust | ||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| FelixFan1122 | C# | |||||||||
| gaosq0604 | Python | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| withaarzoo | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| FelixFan1122 | C# | |||||||||
| gaosq0604 | Python | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| withaarzoo | C++ | |||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 415: Add Strings
- problem 463: Island Perimeter
- problem 541: Reverse String II
- problem 1211: Queries Quality and Percentage
- problem 1251: Average Selling Price
- problem 1280: Students and Examinations
- problem 1327: List the Products Ordered in a Period
- problem 1378: Replace Employee ID With The Unique Identifier
- problem 1407: Top Travellers
- problem 1484: Group Sold Products By The Date
- problem 1517: Find Users With Valid E-Mails
- problem 1527: Patients With a Condition
- problem 1581: Customer Who Visited but Did Not Make Any Transactions
- problem 1587: Bank Account Summary II
- problem 1633: Percentage of Users Attended a Contest
- problem 1661: Average Time of Process per Machine
- problem 1667: Fix Names in a Table
- problem 1683: Invalid Tweets
- problem 1693: Daily Leads and Partners
- problem 1729: Find Followers Count
- problem 1731: The Number of Employees Which Report to Each Employee
- problem 1741: Find Total Time Spent by Each Employee
- problem 1757: Recyclable and Low Fat Products
- problem 1789: Primary Department for Each Employee
- problem 1795: Rearrange Products Table
- problem 1873: Calculate Special Bonus
- problem 1890: The Latest Login in 2020
- problem 1965: Employees With Missing Information
- problem 1978: Employees Whose Manager Left the Company
- problem 2356: Number of Unique Subjects Taught by Each Teacher
- problem 223: Rectangle Area
- problem 240: Search a 2D Matrix II
- problem 318: Maximum Product of Word Lengths
- problem 357: Count Numbers with Unique Digits
- problem 394: Decode String
- problem 1158: Market Analysis I
- problem 1341: Movie Rating
- problem 1492: The kth Factor of n
- problem 1498: Number of Subsequences That Satisfy the Given Sum Condition
- problem 1907: Count Salary Categories
- problem 1934: Confirmation Rate
- problem 2405: Optimal Partition of String
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