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?- A. 0.41(6) -3.(142857) 0.125 0.(81)
- B. 0.41(6) -3.(142857) 0.125 0.(081)
- C. 0.41(6) -4.(857142) 0.125 0.(081)
- 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
- Problem: Fibonacci numbers modulo m repeat with the Pisano period π(m). Use it to get F(10¹⁸) mod 10 without big loops. python def…
- Problem: Compute 3^(5^20) mod p for the prime p = 10⁹ + 7. By Fermat, exponents can be reduced modulo p − 1 (since gcd(3, p) = 1). Which…
- Problem: Two equal-length strings over {x, y}; one move swaps s1[i] with s2[j] (any i, j). Minimum moves to make them equal (−1 if…
- Problem: Rabin–Karp search with a rolling hash: (a) base 10, modulus 7; (b) base 256, modulus 1000003. Count true matches and spurious…
- Problem: A primality helper tries divisors while i·i ≤ n. How many loop iterations run for n = 10⁶ and for n = 99, and what is the…
- Problem: Find the bug: version numbers stored as strings are sorted to find the smallest. What does each sort produce? python…