- Interview Questions
- /
- Problems
- /
- Fraction to Recurring Decimal
Fraction to Recurring Decimal
Turn a fraction into its decimal string, wrapping any repeating digits in parentheses. Really a test of long division and spotting a repeated remainder with a hash map. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given two integers, numerator and denominator. Return the value of numerator / denominator written as a decimal string.
Formatting rules:
- If the division is exact, write it with no decimal point when it is a whole number (
"3"), or with exactly the digits needed otherwise ("1.75"). - If the fractional part repeats forever, write the digits before the repeat as usual and put the repeating block in parentheses, starting at the earliest position where the repetition begins. For example
1/6is"0.1(6)", not"0.(16)"or"0.16(6)". - A negative result starts with
"-". Zero is always"0", never"-0".
The answer is unique under these rules, and it is guaranteed to be shorter than 10⁴ characters.
Example 1
- Input
- numerator = 7, denominator = 4
- Output
- "1.75"
Example 2
- Input
- numerator = -22, denominator = 7
- Output
- "-3.(142857)"
22 / 7 = 3.142857142857..., and the block 142857 repeats.
Example 3
- Input
- numerator = 1, denominator = 6
- Output
- "0.1(6)"
The 1 appears once, then 6 repeats forever.
Example 4
- Input
- numerator = 0, denominator = -5
- Output
- "0"
Constraints
- -2³¹ ≤ numerator, denominator ≤ 2³¹ - 1
- denominator ≠ 0
- The answer has fewer than 10⁴ characters.
Practice
Runs 16 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Fraction to Recurring Decimal in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Fraction to Recurring Decimal
Pattern: Long division with a remainder map
Do the division the way you would on paper. After the integer part, each step multiplies the remainder by 10, writes one digit (remainder * 10 // d), and keeps the new remainder (remainder * 10 % d).
The next digit depends only on the current remainder. So the moment a remainder shows up a second time, everything from its first appearance onward will repeat forever. Remember, for each remainder, the position in the digit list where it first appeared. When you see it again, insert ( at that position and ) at the end. If the remainder reaches 0 instead, the decimal terminates.
Because every remainder is between 1 and d - 1, a repeat is guaranteed within d steps.
Approach 1: Long division, search past remainders linearly
Same long division, but keep remainders in a list and scan it each step to look for a repeat. Correct, but with a long period (like 1/7919, period 3959) the repeated scans add up.
Time O(p²), p = number of fractional digits · Space O(p)
Approach 2: Long division with a hash map
- Handle 0, then record the sign and switch to absolute values.
- Append the integer part
n // d. Ifn % d == 0, you're done. - Append
.and loop while the remainder is non-zero: if it is already in the map, wrap the digits from the stored index in parentheses and stop; otherwise storeremainder → current digit index, then emit the next digit and update the remainder.
Time O(p) · Space O(p)
| Approach | Time | Space |
|---|---|---|
| Long division, search past remainders linearly | O(p²), p = number of fractional digits | O(p) |
| Long division with a hash map | O(p) | O(p) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Fraction to Recurring Decimal solution in Python
def fraction_to_decimal(numerator: int, denominator: int) -> str:
if numerator == 0:
return "0"
parts = []
if (numerator < 0) != (denominator < 0):
parts.append("-")
n, d = abs(numerator), abs(denominator)
parts.append(str(n // d))
remainder = n % d
if remainder == 0:
return "".join(parts)
parts.append(".")
digits = []
seen = {} # remainder -> index in digits where it first appeared
while remainder and remainder not in seen:
seen[remainder] = len(digits)
remainder *= 10
digits.append(str(remainder // d))
remainder %= d
if remainder:
start = seen[remainder]
digits.insert(start, "(")
digits.append(")")
return "".join(parts) + "".join(digits)Fraction to Recurring Decimal solution in JavaScript
function fractionToDecimal(numerator, denominator) {
if (numerator === 0) return '0';
let result = (numerator < 0) !== (denominator < 0) ? '-' : '';
const n = Math.abs(numerator);
const d = Math.abs(denominator);
result += Math.floor(n / d);
let remainder = n % d;
if (remainder === 0) return result;
result += '.';
const digits = [];
const seen = new Map(); // remainder -> index in digits where it first appeared
while (remainder !== 0 && !seen.has(remainder)) {
seen.set(remainder, digits.length);
remainder *= 10;
digits.push(Math.floor(remainder / d));
remainder %= d;
}
if (remainder !== 0) {
digits.splice(seen.get(remainder), 0, '(');
digits.push(')');
}
return result + digits.join('');
}Common mistakes
- Taking the absolute value of -2³¹ in a 32-bit integer, which overflows. Use a 64-bit type (in Java or C++) before negating.
- Producing `"-0"` or a stray minus sign when the numerator is 0.
- Computing the sign from `numerator * denominator < 0`, which can overflow in fixed-width languages. Compare the signs separately instead.
- Recording the remainder after emitting its digit instead of before, which puts the opening parenthesis one position too late.
- Using floating-point division, which loses precision and cannot detect a repeat.
What interviewers look for
Start with the key observation: "the next digit depends only on the remainder, so a repeated remainder means a repeating cycle." That sentence is what the interviewer is waiting for.
Then list the edge cases before coding: zero numerator, negative signs on either side, the -2³¹ overflow, and whole-number results with no decimal point. Trace 1/6 to show the parenthesis lands after the 1.
Follow-up questions
How long can the repeating part be?
At most `d - 1` digits, since there are only `d - 1` non-zero remainders. The exact length is the multiplicative order of 10 modulo the part of `d` with factors of 2 and 5 removed.
How would you convert a repeating decimal string back into a fraction?
For `0.a(b)` with `a` of length k and `b` of length r, the value is `(ab - a) / (10^k · (10^r - 1))`, where `ab` and `a` are read as integers. Reduce by the gcd. Add the integer part and sign afterward.
Can you tell in advance whether the decimal terminates?
Yes. Reduce the fraction by the gcd. It terminates exactly when the reduced denominator has no prime factors other than 2 and 5, and the number of fractional digits is the larger of the two exponents.
Companies that ask Fraction to Recurring Decimal
Fraction to Recurring Decimal is tagged by 90 companies in our interview dataset. The score shows how often it comes up at each company.
- C3.ai100%
- Cedar100%
- Datavant100%
- SpaceX94%
- Genentech93%
- Mercado Libre93%
- Adesso89%
- Ixl Learning88.8%
- Rally Health84%
- Myriad Genetics84%
- Dish Network84%
- Quantcast84%
- Ramp83%
- Rackspace82%
- Nubank81%
- Viasat81%
- Checkr81%
- Appian79%
- Swiss Re79%
- Goldman Sachs76.9%
- Mailchimp75%
- Hopper75%
- Floqast74%
- Astera Labs74%
and 66 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required