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?- A. 3
- B. 2
- C. 1
- 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
- Problem: Count the connected components of the undirected graph on 6 vertices with edges (0,1), (1,2), (3,4), (5,5) using DFS. Run the…
- Problem: Check whether the directed graph with edges 0->1, 1->2, 2->0, 2->3 contains a cycle using Kahn's algorithm (count the nodes that…
- Problem: Find the minimum cost to reach node 3 from node 0 using at most 2 edges in the directed graph with edges (0,1,5), (1,3,5)…
- Problem: Count the nodes at depth exactly 2 in the rooted tree with children 0: [1, 2], 1: [3], 2: [4, 5], 3: [], 4: [], 5: []. Root 0 has…
- Problem: How many integers from 1 to 1000 are divisible by 3 or by 5 but not by both?
- Problem: What is the product of the distinct prime factors of 360? Run the code. python n = 360 p, prod = 2, 1 while p p <= n: if n % p ==…