Fraction to Recurring Decimal (LeetCode 166): Solution and Explanation

Medium
Hash Table
Math
String

Given a numerator and a denominator, return the fraction as a decimal string, putting any repeating block of digits in parentheses, such as 0.(012) for 4 / 333.

Intuition

Long division by hand produces one digit at a time: take the remainder, multiply by 10, divide by d, write the digit, keep the new remainder.

The digit and the next remainder depend only on the current remainder. So if a remainder ever shows up a second time, everything after it replays exactly, forever.

There are only d possible remainders (0 to d - 1), so within d steps the division either reaches remainder 0 and terminates, or repeats a remainder.

Store every remainder together with the position of the digit it produced. When a remainder comes back, its stored position is where the repeating block starts, which is where the opening parenthesis goes.

Approach: Long division with a remainder to position map

  1. If the numerator is 0, return "0".
  2. Prepend "-" when exactly one of the two numbers is negative, then continue with absolute values in 64-bit integers.
  3. Write the integer part n / d. If n % d is 0, return now.
  4. While the remainder is not 0 and not in seen: set seen[rem] to the current digit position, multiply rem by 10, write rem / d, and set rem = rem % d.
  5. If the loop ended on a seen remainder, insert "(" at seen[rem] and append ")".

Step-by-step example

numerator = 4, denominator = 333
  1. Both are positive, so there is no sign. 4 / 333 = 0 remainder 4, so the integer part is 0.
  2. Remainder 4 is new: seen[4] = 0. 40 / 333 = 0 remainder 40, write 0.
  3. Remainder 40 is new: seen[40] = 1. 400 / 333 = 1 remainder 67, write 1.
  4. Remainder 67 is new: seen[67] = 2. 670 / 333 = 2 remainder 4, write 2.
  5. Remainder 4 is already in seen at position 0, so digits 0 to 2 repeat. The answer is "0.(012)".

Code: Python, Java, C++

1class Solution:
2    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
3        if numerator == 0:
4            return "0"
5        sign = "-" if (numerator < 0) != (denominator < 0) else ""
6        n, d = abs(numerator), abs(denominator)
7        whole, rem = divmod(n, d)
8        if rem == 0:
9            return sign + str(whole)
10        digits = []
11        seen = {}
12        while rem and rem not in seen:
13            seen[rem] = len(digits)
14            rem *= 10
15            digits.append(str(rem // d))
16            rem %= d
17        frac = "".join(digits)
18        if rem:
19            start = seen[rem]
20            frac = frac[:start] + "(" + frac[start:] + ")"
21        return sign + str(whole) + "." + frac
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(d)

Each loop step produces a new remainder, and there are at most d distinct remainders, so the loop runs at most d times (bounded further by the 10^4 answer length).

Space

O(d)

The map holds one entry per fraction digit written, and the answer string has the same length.

Other approaches

Detect the cycle with slow and fast remainders (time O(d), space O(1) besides the output)

Treat rem -> rem * 10 % d as a function and use Floyd's cycle detection to find where the cycle starts, then build the string. It avoids the map but needs extra passes and is harder to get right.

Factor the denominator (time O(d), space O(1) besides the output)

After reducing the fraction, the non-repeating prefix length is the larger exponent of 2 and 5 in d, and the cycle length is the order of 10 modulo the rest. Elegant number theory, but far more code than a map.

Common mistakes

  • Taking the absolute value in 32-bit. abs(-2147483648) overflows, so cast to 64-bit first.
  • Getting the sign wrong for results with a zero integer part, such as 7 / -12 = "-0.58(3)". Build the sign from the inputs, not from the integer part.
  • Producing "-0" when the numerator is 0 and the denominator is negative. Return "0" before handling the sign.
  • Recording the remainder after multiplying by 10 instead of before. The map must key on the remainder that produces the digit at that position.

Frequently asked questions

Why does a repeated remainder guarantee a repeating decimal?

The next digit and the next remainder are computed from the current remainder alone. Once a remainder repeats, the same sequence of digits and remainders follows again, so the block between the two occurrences repeats forever.

Why store the remainder and not the digit?

The same digit can appear in different contexts. In 1 / 6 = 0.1(6) the digit pattern alone does not tell you when the cycle starts, but the remainder 4 repeating does.

Can the loop run forever?

No. There are at most d different non-zero remainders, so after at most d steps either the remainder is 0 or one repeats.

Why use 64-bit integers?

The numerator can be -2^31, whose absolute value is 2^31 and does not fit in a 32-bit int. Also rem * 10 can reach about 2 * 10^10.