☰ All problems

Word Break

Screen readers stumble over hashtags such as #sunsetbeachday because the words run together. A social app wants to know whether a lowercase hashtag s can be split into words from its dictionary, wordDict.

Return true if s can be cut into one or more pieces where every piece is a dictionary word, and false otherwise. A dictionary word may be used any number of times, and not every word has to be used.

Example 1
Input: s = "sunsetbeachday", wordDict = ["sun","set","sunset","beach","day"]
Output: true

Explanation: sunset + beach + day works, and so does sun + set + beach + day.

Example 2
Input: s = "gogogo", wordDict = ["go"]
Output: true

Explanation: The same word can be used again and again.

Example 3
Input: s = "seashells", wordDict = ["sea","seas","shell","hell"]
Output: false

Explanation: Both sea + shell and seas + hell leave a stray s at the end.

Constraints

  • s is between 1 and 300 characters long.
  • wordDict holds between 1 and 1000 distinct words, each 1 to 20 characters long.
  • s and every dictionary word use only lowercase English letters.

Follow-up: How would you list every possible way to split the hashtag, instead of only reporting whether one exists?

💡 Hint 1

Trying every possible first word and recursing is correct but can be exponential: the same suffix gets re-checked many times.

💡 Hint 2

Let ok[i] mean "the first i characters can be segmented". ok[0] is true.

💡 Hint 3

ok[i] is true if some j < i has ok[j] true and s.slice(j, i) in the dictionary. Put the words in a hash set, and only look back as far as the longest word.

/**
 * @param {string} s
 * @param {string[]} wordDict
 * @return {boolean}
 */
function wordBreak(s, wordDict) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc