Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count the ways to split s into a sequence of dictionary words.
Problem: Count the ways to split s into a sequence of dictionary words.
def count(s, words):
W = set(words); dp = [1] + [0] * len(s)
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j:i] in W: dp[i] += dp[j]
return dp[-1]
print(count("studyclipnow", ["study", "clip", "studyclip", "now", "no", "w", "clipnow"]))What is printed?- A. 3
- B. 5
- C. 4
- D. 6
Correct answer: B. 5
Splits: study|clip|now, study|clip|no|w, study|clipnow, studyclip|now, studyclip|no|w, so 5. dp[i] adds dp[j] for every dictionary word s[j:i], which counts each split exactly once.
More Coding Interview Problems questions
- Problem: Regular-expression matching where '.' matches any one character and 'x' matches zero or more x (the whole string must match)…
- Problem: Count how many distinct index sequences of s spell t as a subsequence. python def distinct(s, t): dp = [1] + [0] len(t) for c in…
- Problem: Maximum profit from at most 2 buy-sell transactions (sell before buying again). python def two(p): b1 = b2 = float('-inf'); s1 =…
- Problem: A courier starts at depot 0, must visit every city exactly once and return to 0. Solve it with bitmask DP (Held–Karp). python INF…
- Problem: Sum a[i] XOR a[j] over all pairs i < j in O(n · bits) by counting, for each bit, how many numbers have it set. python def…
- Edge case: nCr mod p is computed with factorials and Fermat inverses. Here n ≥ p. python p = 7 fact = [1] 11 for i in range(1, 11)…