Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses.
Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses.
def frac(n, d):
q, r = divmod(n, d); s = str(q)
if r == 0: return s
s += "."; seen = {}; digits = []
while r and r not in seen:
seen[r] = len(digits); r *= 10
digits.append(str(r // d)); r %= d
if r:
i = seen[r]; return s + "".join(digits[:i]) + "(" + "".join(digits[i:]) + ")"
return s + "".join(digits)
print(frac(5, 74), frac(7, 12))What is printed?- A. 0.(067) 0.58(3)
- B. 0.0(675) 0.(583)
- C. 0.0(675) 0.58(3)
- D. 0.06(756) 0.5(83)
Correct answer: C. 0.0(675) 0.58(3)
The cycle starts at the digit produced from the first remainder that recurs. 5/74 = 0.0675675…: remainders go 50, 56, 42, 50, so the cycle 675 begins after the first 0. 7/12 = 0.58333…: remainder 4 repeats, so only the 3 is in the cycle.
More Coding Interview Problems questions
- Generating all permutations of n distinct items with backtracking and copying each complete permutation into the result list costs how…
- A disjoint-set forest uses path compression but NO union by rank/size. What is its amortised cost per operation over m operations on n…
- What is the running time of Dijkstra's algorithm with a Fibonacci heap on a graph with V vertices and E edges?
- For an array of n = 10⁶ integers, report the number of DISTINCT values in every window of k = 10⁵ consecutive elements. Which approach is…
- n = 10⁵ points are given, followed by q = 10⁵ OFFLINE queries 'how many points lie in the axis-aligned rectangle [x1, x2] × [y1, y2]?'…
- Edge case: integer division and modulo with negative operands in Python. python print(-7 // 2, -7 % 2, int(-7 / 2)) What is printed?