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?- A. 12 15 24
- B. 12 16 24
- C. 10 16 24
- 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
- Problem: A chess knight hops on a phone keypad (1-9 in a 3 × 3 grid, 0 below 8). Count the distinct numbers of length n it can dial (start…
- Problem: Trade a stock any number of times (hold at most one share); each completed sale pays a fixed fee. Maximise profit with two…
- Problem: Is c formed by interleaving a and b (keeping each string's internal order)? dp[i][j] = first i chars of a and j chars of b can…
- Problem: Wildcard matching over the whole string: '?' matches any one character, '' matches any sequence (including empty). python def…
- Problem: Return (length of the longest strictly increasing subsequence, number of such longest subsequences). python def numlis(a): n =…
- Problem: With k identical eggs and an n-floor building, find the minimum number of drops that guarantees finding the critical floor. DP on…