Data Structures & AlgorithmsHardProduct Company SDE · DP round

Problem: How many distinct ways can the string 'leetcode' be segmented into words from the dictionary {'leet', 'code', 'leetcode', 'lee', 't'}? Count segmentations with the DP below.

Problem: How many distinct ways can the string 'leetcode' be segmented into words from the dictionary {'leet', 'code', 'leetcode', 'lee', 't'}? Count segmentations with the DP below.
s = 'leetcode'
d = {'leet', 'code', 'leetcode', 'lee', 't'}
ways = [1] + [0] * len(s)
for i in range(1, len(s) + 1):
    for j in range(i):
        if s[j:i] in d:
            ways[i] += ways[j]
print(ways[len(s)])
What is printed?
  1. A. 3
  2. B. 2
  3. C. 1
  4. D. 4

Correct answer: A. 3

The segmentations are leetcode, leet + code and lee + t + code, giving 3. The count is the DP over every last-word split point.

More Coding Interview Problems questions

Exams that ask this topic