Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Ugly numbers have no prime factors other than 2, 3 and 5. Generate them in order with three pointers.
Problem: Ugly numbers have no prime factors other than 2, 3 and 5. Generate them in order with three pointers.
def ugly(n):
u = [1]; i2 = i3 = i5 = 0
while len(u) < n:
nx = min(u[i2] * 2, u[i3] * 3, u[i5] * 5); u.append(nx)
if nx == u[i2] * 2: i2 += 1
if nx == u[i3] * 3: i3 += 1
if nx == u[i5] * 5: i5 += 1
return u[n-1]
print(ugly(15))What is printed?- A. 24
- B. 20
- C. 25
- D. 27
Correct answer: A. 24
Sequence: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, so the 15th is 24. Advancing every pointer that produced the minimum (not just one) avoids duplicates such as 6 = 2·3 = 3·2.
More Coding Interview Problems questions
- Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses. python def frac(n, d): q, r = divmod(n, d); s =…
- 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]?'…