Problem 166

Abstract / Summary

Given a numerator and denominator, output the decimal representation of the fraction, including recurring parts in parentheses.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
39 lines | 1212 bytes | submitted September 7, 2023 | GitHub   14% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 31% (1+ million submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.89 | σ = 1.69

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
44 links | 28 authors | 9 languages

Videos

15 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

30 easy 12 medium
43 solutions   September 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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