Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses: remember at which output position each remainder first appeared.

Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses: remember at which output position each remainder first appeared.
def frac(num, den):
    sign = "-" if num * den < 0 else ""
    num, den = abs(num), abs(den)
    q, r = divmod(num, den)
    if r == 0: return sign + str(q)
    seen, dec = {}, []
    while r and r not in seen:
        seen[r] = len(dec); r *= 10
        dec.append(str(r // den)); r %= den
    if r: dec.insert(seen[r], "("); dec.append(")")
    return sign + str(q) + "." + "".join(dec)
print(frac(5, 12), frac(-22, 7), frac(1, 8), frac(3, 37))
What is printed?
  1. A. 0.41(6) -3.(142857) 0.125 0.(81)
  2. B. 0.41(6) -3.(142857) 0.125 0.(081)
  3. C. 0.41(6) -4.(857142) 0.125 0.(081)
  4. D. 0.4(16) -3.(142857) 0.125 0.(081)

Correct answer: B. 0.41(6) -3.(142857) 0.125 0.(081)

Long division: a remainder that repeats means the digits since its first appearance repeat. 5/12: remainders 5 → 2 → 8 → 8… so digits 4, 1, then 6 repeating → 0.41(6), not 0.4(16). −22/7: work with absolute values (Python's floor division would give −4) → −3.(142857). 1/8 terminates. 3/37 = 0.081081… → (081) – the leading 0 is part of the cycle. At most den distinct remainders → O(den).

More Coding Interview Problems questions

Exams that ask this topic