Word Break

Medium#1391d array

You get a string and a list of words. Can the string be cut into pieces so that every piece is a word from the list? A word may be used many times. Our example: "seashell" with the words sea, seas, hell — yes, seas + hell.

input
s: a string; wordDict: a list of different words.
returns
true if s can be cut into words of wordDict, each of them used any number of times; false if not.
constraints
  • 1 ≤ s.length ≤ 200
  • 1 ≤ wordDict.length ≤ 1000
  • 1 ≤ wordDict[i].length ≤ 20
  • s, wordDict[i]: lowercase English letters
  • the words of wordDict are all different
our 15 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {string} s
 * @param {string[]} wordDict
 * @return {boolean}
 */
function wordBreak(s, wordDict) {

}
Ctrl ↵
format
reset

saved in this browser

15 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more dynamic programming (dp) problems

Pattern “Dynamic programming (DP)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.