Word Break

Medium1-D dynamic programming

Given a string s and a list of words wordDict, return true if s can be cut into pieces that are each a word from the list, and false otherwise.

A word can be used any number of times.

Examples

Example 1
Input:  s = "sunflower", wordDict = ["sun", "flower"]
Output: true

sun + flower.

Example 2
Input:  s = "carpets", wordDict = ["car", "pet", "carp"]
Output: false

car + pet leaves s, and carp leaves ets. Neither is a word.

Constraints

  • 1 ≤ s.length ≤ 300
  • 1 ≤ wordDict.length ≤ 1000
  • 1 ≤ wordDict[i].length ≤ 20
  • s and the words hold lowercase English letters only, and the words are all different.

Stuck?

Hint 1

Taking the first word that matches can lead you down a dead end. Ask instead, for every prefix of s: can this prefix be cut into words?

Hint 2

Prefix i can be cut if some shorter prefix j can be and s.slice(j, i) is a word. Put the words in a Set and fill a list of booleans from the empty prefix up.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur