iq.lab
Python starts when a code cell comes near or you run one
mediumDynamic programming, 1D target 25 min

Word break

You get a string s of lowercase letters and a list words of dictionary words. Return True if you can cut s into pieces so that every piece is one of the words, and False otherwise.

  • The pieces must cover all of s, in order: no letter left over, and no letter in two pieces.
  • A word may be used any number of times, or not at all.
Example 1
Inputs = "sunflower", words = ["sun", "flow", "flower"]OutputTrue

Cut it as "sun" + "flower". The cut "sun" + "flow" would leave "er", which is not a word.

Example 2
Inputs = "redbluered", words = ["red", "blue"]OutputTrue

"red" + "blue" + "red": the word "red" is used twice.

Example 3
Inputs = "bookend", words = ["book", "boo", "kend"]OutputTrue

"boo" + "kend". Taking the longer "book" first leaves "end", which cannot be cut.

Example 4
Inputs = "seashells", words = ["sea", "seas", "hell", "shell"]OutputFalse

Both ways to cover "seashell" ("sea" + "shell" and "seas" + "hell") leave a lone "s" at the end.

Constraints
  • 1 ≤ len(s) ≤ 300

  • 1 ≤ len(words) ≤ 1,000

  • 1 ≤ len(word) ≤ 20 for every word

  • s and the words use only lowercase English letters, and the words are all different.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.