Fraction to Recurring Decimal

MediumMathlong division with hashing

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given two integers numerator and denominator, return the value of the fraction as a decimal string. If the fractional part terminates, write it out in full with no trailing zeros (and omit the decimal point entirely for whole numbers). If it repeats, write the non-repeating digits followed by the **shortest** repeating block wrapped in parentheses, starting at the earliest possible position, e.g. "0.1(6)" rather than "0.16(6)" or "0.(16)". Prefix a - only when the value is negative; zero is "0". Watch for overflow when negating -2^31. The answer is guaranteed to be shorter than 10^4 characters.

Examples

Input: numerator = 1, denominator = 2
Output: "0.5"
1/2 terminates after one digit.
Input: numerator = 2, denominator = 1
Output: "2"
A whole number has no decimal point.
Input: numerator = 4, denominator = 333
Output: "0.(012)"
4/333 = 0.012012012..., so the block 012 repeats from the first decimal digit.

Constraints

  • -2^31 <= numerator, denominator <= 2^31 - 1
  • denominator != 0
  • the answer string has length < 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.