FastPrepWord Break

Word Break

Google logoGoogle● MediumINTERNONSITE INTERVIEW
Learn

Problem statement

Given a string s and an array of dictionary words wordDict, return true if s can be split into a sequence of one or more dictionary words. Otherwise, return false.

All words in wordDict are available for the entire call, and a word may be reused multiple times. Dictionary membership uses exact string equality; duplicate entries do not change the result.

Function

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

Examples

Example 1

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

Split s as leet + code. Both pieces belong to wordDict.

Example 2

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

The prefixes cats and cat both lead to suffixes that cannot be fully segmented.

Example 3

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

Split s as apple + pen + apple. Reusing apple is allowed.

Constraints

  • 1 <= s.length <= 300.
  • 1 <= wordDict.length <= 1000.
  • 1 <= wordDict[i].length <= 20.
  • Every dictionary entry is non-empty.

More Google problems

See Google hiring insights
public boolean wordBreak(String s, String[] wordDict) {
  // Write your code here.
}
s"leetcode"
wordDict["leet","code"]
expectedtrue
Checking account…