Word Break

35 min · wordBreak()

A message can contain only familiar words and still be impossible to split cleanly. One stubborn letter is enough to ruin every proposed reading.

Given a lowercase string s and a list of unique lowercase words wordDict, return true exactly when all of s can be assembled from dictionary words placed end to end. This complete split is a segmentation: a sequence of one or more words whose concatenation equals the original string.

A few ground rules:

  • You must cover every character of s; no gaps or leftovers are allowed.
  • A dictionary word may be reused as many times as you need.
  • You only return whether a segmentation exists, not the words that form it.

Constraints

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1_000
  • 1 <= wordDict[i].length <= 20
  • s and every dictionary word contain only lowercase English letters.
  • All words in wordDict are unique.

Hints

Choose the next cut

Stand at the first uncovered character. Try every later cut whose slice is in the dictionary, then ask the same question from that cut onward.

Remember dead ends

Different choices can bring you to the same character position. Once you know that the suffix starting there can't be segmented, don't solve that suffix again.

Turn the view around

Let dp[i] answer whether the first i characters can be segmented. To prove dp[i], find an earlier reachable boundary j where s[j:i] is a dictionary word.

Follow-up

How would you return one valid sequence of words instead of only true or false?

Visible cases

Examples

Example 1

ready
Input
s = "leetcode"
wordDict = [
  "leet",
  "code"
]
Expected
true
Why
'leet' followed by 'code' covers the whole string

Example 2

ready
Input
s = "applepenapple"
wordDict = [
  "apple",
  "pen"
]
Expected
true
Why
'apple' can be reused on both sides of 'pen'

Example 3

ready
Input
s = "catsandog"
wordDict = [
  "cats",
  "dog",
  "sand",
  "and",
  "cat"
]
Expected
false
Why
every promising split leaves uncovered characters

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite