Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Numbers whose only prime factors are 2, 3 and 5 (1 included) are generated in order with three pointers.

Problem: Numbers whose only prime factors are 2, 3 and 5 (1 included) are generated in order with three pointers.
def ugly(n):
    u = [1]; i2 = i3 = i5 = 0
    while len(u) < n:
        nxt = min(u[i2] * 2, u[i3] * 3, u[i5] * 5); u.append(nxt)
        if nxt == u[i2] * 2: i2 += 1
        if nxt == u[i3] * 3: i3 += 1
        if nxt == u[i5] * 5: i5 += 1
    return u[-1]
print(ugly(10), ugly(12), ugly(15))
What is printed?
  1. A. 12 15 24
  2. B. 12 16 24
  3. C. 10 16 24
  4. D. 12 16 25

Correct answer: B. 12 16 24

Each new value is the smallest of (next value ×2, ×3, ×5); all matching pointers advance, so 6 = 2·3 = 3·2 is produced once (using elif would insert duplicates). Sequence: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24 → 10th = 12, 12th = 16, 15th = 24 (7, 11, 14 are skipped). O(n).

More Coding Interview Problems questions

Exams that ask this topic