Problem · String

Word Break with a Reusable Dictionary

Learn this problem
MediumMeta logoMetaFULLTIMEONSITE INTERVIEW
See Meta hiring insights

Problem statement

Given a string s and a set of nonempty dictionary words, return whether s can be segmented into a sequence of one or more dictionary words.

Each dictionary word may be reused any number of times. The segmentation must cover the entire string in order. The empty string is segmentable using zero words.

Function

wordBreak(s: String, dictionary: String[]) → boolean

Examples

Example 1

s = "leetcode"dictionary = ["leet","code"]return = true

Split the string as leet | code.

Example 2

s = "applepenapple"dictionary = ["apple","pen"]return = true

The word apple is reused in apple | pen | apple.

Example 3

s = "catsandog"dictionary = ["cats","dog","sand","and","cat"]return = false

Every possible prefix decomposition leaves a suffix that is not in the dictionary.

Constraints

  • 0 <= s.length <= 5000.
  • 0 <= dictionary.length <= 5000.
  • 1 <= dictionary[i].length <= 100.
  • s and every dictionary word contain only lowercase English letters.
  • Dictionary words are unique.

More Meta problems

drafts saved locally
public boolean wordBreak(String s, String[] dictionary) {
    // Write your code here.
}
s"leetcode"
dictionary["leet","code"]
expectedtrue
checking account