Data Structures & AlgorithmsHardProduct Company SDE · DP round
Problem: How many ways can the digit string '226' be decoded when 1 maps to A, 2 to B, ..., 26 to Z? Run the DP.
Problem: How many ways can the digit string '226' be decoded when 1 maps to A, 2 to B, ..., 26 to Z? Run the DP.
s = '226'
dp = [1] * (len(s) + 1)
for i in range(2, len(s) + 1):
cur = 0
if s[i - 1] != '0':
cur += dp[i - 1]
if 10 <= int(s[i - 2:i]) <= 26:
cur += dp[i - 2]
dp[i] = cur
print(dp[len(s)])What is printed?- A. 2
- B. 4
- C. 1
- D. 3
Correct answer: D. 3
The decodings are BBF (2,2,6), BZ (2,26) and VF (22,6), so there are 3. A zero digit alone cannot be decoded, which is why the code checks s[i - 1] != '0'.
More Coding Interview Problems questions
- Problem: Union-find with path compression and union by rank performs m operations on n elements in what amortised time per operation?
- Problem: What is the largest rectangle area that can be formed in a histogram of heights [2, 1, 5, 6, 2, 3]? Use the stack code. python h…
- Problem: What is the minimum number of operations to sort the array [4, 3, 2, 1] using only swaps of adjacent elements? Run the code…
- Problem: Consider a graph where you must find the minimum 'maximum edge' on a path from s to t (a bottleneck path). Which algorithm…
- Problem: For a segment tree with n leaves supporting range-sum queries and point updates, what is the total space needed in terms of n?
- Problem: Find the number of inversions in [5, 4, 3, 2, 1] that a merge-sort based counter would report. Run the code. python def count(a)…