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?
  1. A. 24
  2. B. 20
  3. C. 25
  4. 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

Exams that ask this topic