Data Structures & AlgorithmsModerateProduct Company SDE · DP round
Problem: How many ways are there to decode the digit string '111' (1 maps to A, ..., 26 maps to Z)? Run the DP.
Problem: How many ways are there to decode the digit string '111' (1 maps to A, ..., 26 maps to Z)? Run the DP.
s = '111'
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. 3
- C. 4
- D. 5
Correct answer: B. 3
dp[i] adds dp[i − 1] when the last digit is 1-9 and dp[i − 2] when the last two digits form 10-26, giving dp = 1, 1, 2, 3: AAA, KA (11, 1) and AK (1, 11). Forgetting that the two-digit 11 can sit at either end gives the tempting 2.
More Coding Interview Problems questions
- Problem: What is the length of the longest substring without repeating characters in 'pwwkew'? Run the sliding-window code. python s =…
- Problem: How many distinct permutations (rearrangements as strings) of 'aabc' exist? Run the code. python from itertools import…
- Problem: What is the sum of C(10, k) over all even k from 0 to 10? Run the code. python from math import comb print(sum(comb(10, k) for k…
- Problem: How many integers in [100, 999] have all three digits distinct? Run the code. python print(sum(1 for x in range(100, 1000) if…
- Problem: What is the length of the longest strictly increasing contiguous run in [1, 3, 5, 4, 7, 8, 2]? Run the code. python a = [1, 3, 5…
- Problem: What is the maximum nesting depth of parentheses in '(1+(23)+((8)/4))+1'? Run the code. python s = '(1+(23)+((8)/4))+1' depth =…