CodeArchon

medium1-D Dynamic ProgrammingFacebookAmazonGoogle

Dictionary Breaker

A tokenizer checks whether a run-on string can be chopped into a sequence of dictionary words.

Given a string s and a dictionary of words, return true if s can be segmented into one or more dictionary words.

Choose approach

1
0
0
1
?
2
?
3
?
4
?
5
?
6
?
7
?
8
i
1/9
Narrationstep 1 of 9

dp[1] = F (prefix "l")

1def wordBreak(s, wordDict):
2 S = set(wordDict)
3 dp = [False] * (len(s) + 1); dp[0] = True
4 for i in range(1, len(s) + 1):
5 for j in range(i):
6 if dp[j] and s[j:i] in S:
7 dp[i] = True; break
8 return dp[len(s)]
Variables
i=1
breakable=false

How to think about it

  1. Reduce to reachability on a string of prefix endpoints.
  2. Trie preprocessing can speed inner check.

Edge cases to catch in interview

  • Empty s -> true.
  • No dict word is prefix of s -> false.

Examples

Example 1true
{"s":"applepenapple","wordDict":["apple","pen"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed