Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Count the ways to decode a digit string where 'A' = 1 … 'Z' = 26.
Problem: Count the ways to decode a digit string where 'A' = 1 … 'Z' = 26.
def decode(s):
prev2, prev1 = 1, (1 if s[0] != '0' else 0)
for i in range(1, len(s)):
cur = 0
if s[i] != '0': cur += prev1
if 10 <= int(s[i-1:i+1]) <= 26: cur += prev2
prev2, prev1 = prev1, cur
return prev1
print(decode("226"), decode("2101"), decode("06"), decode("1111"))What is printed?- A. 3 1 0 5
- B. 3 2 0 5
- C. 3 1 1 5
- D. 2 1 0 5
Correct answer: A. 3 1 0 5
One digit is valid unless it is 0; two digits are valid if 10..26. "226" → 2-2-6, 22-6, 2-26. "2101": the 0 must pair as 10, then 1 alone: 2-10-1 only. "06" has no valid start. "1111" gives Fibonacci 5. O(n), O(1).
More Coding Interview Problems questions
- Problem: Decide whether a string can be split into words from a dictionary. python def wb(s, words): W = set(words); dp = [True] + [False]…
- Problem: Return the maximum product of a contiguous subarray (values may be negative or zero). python def maxprod(a): hi = lo = best =…
- Problem: Can an array be split into two subsets with equal sums? python def cansplit(a): s = sum(a) if s % 2: return False reach = 1 for x…
- Problem: Return the length of the longest palindromic subsequence (not substring). python def lps(s): n = len(s); dp = [[0] n for in…
- Problem: Multiply a chain of matrices with dimensions given as p (matrix i is p[i−1] × p[i]) using the fewest scalar multiplications…
- Problem: A DP solution for 'minimum coins for amount A using c denominations' with A ≤ 10⁴ and c ≤ 100 is accepted. A friend proposes…