FastPrepWord Break

Word Break

Moveworks logoMoveworks● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

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

A dictionary word may be reused any number of times.

Function

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

Examples

Example 1

s = "prepcode"wordDict = ["prep","code"]return = true

The string splits as prep + code.

Example 2

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

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

Example 3

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

No sequence of dictionary words covers the entire string.

Constraints

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

More Moveworks problems

See Moveworks hiring insights
public boolean wordBreak(String s, String[] wordDict) {
  // write your code here
}
s"prepcode"
wordDict["prep","code"]
expectedtrue
Checking account…