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?
  1. A. 3
  2. B. 5
  3. C. 4
  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

Exams that ask this topic