Dynamic Programming
Word Break
DESCRIPTION (inspired by Leetcode.com)
You are provided with a string s and a set of words called wordDict. Write a function to determine whether s can be broken down into a sequence of one or more words from wordDict, where each word can appear more than once and there are no spaces in s. If s can be segmented in such a way, return true; otherwise, return false.
Input:
s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output:
false
Explanation: There is no valid segmentation of "catsandog" into dictionary words from wordDict.
Input:
s = "hellointerview", wordDict = ["hello","interview"]
Output:
true
Explanation: Return true because "hellointerview" can be segmented as "hello" and "interview".
Note that you are allowed to reuse a dictionary word.
Run your code to see results here
Have suggestions or found something wrong?
Explanation
def wordBreak(s, wordDict):wordSet = set(wordDict)dp = [False] * (len(s) + 1)dp[0] = True # Empty string is a valid breakfor i in range(1, len(s) + 1):for j in range(i):sub = s[j:i]if dp[j] and sub in wordSet:dp[i] = Truebreakreturn dp[len(s)]
word break
0 / 1
def wordBreak(s, wordDict):wordSet = set(wordDict)dp = [False] * (len(s) + 1)dp[0] = True # Empty string is a valid breakfor i in range(1, len(s) + 1):for j in range(i):sub = s[j:i]if dp[j] and sub in wordSet:dp[i] = Truebreakreturn dp[len(s)]
i = 1
0 / 11
What is the time complexity of this solution?
O(m * n)
O(n!)
O(n²)
O(n log n)
Solution
def wordBreak(s, wordDict):wordSet = set(wordDict)dp = [False] * (len(s) + 1)dp[0] = True # Empty string is a valid breakfor i in range(1, len(s) + 1):for j in range(i):sub = s[j:i]if dp[j] and sub in wordSet:dp[i] = Truebreakreturn dp[len(s)]
word break
0 / 88
Alternative Solution
def wordBreak(s, wordDict):dp = [False] * (len(s) + 1)dp[0] = True # Empty string is a valid breakfor i in range(1, len(s) + 1):for word in wordDict:if i >= len(word) and dp[i - len(word)]:sub = s[i - len(word):i]if sub == word:dp[i] = Truebreakreturn dp[len(s)]
word break
0 / 65
What is the time complexity of this solution?
O(4ⁿ)
O(n!)
O(n * m)
O(V + E)
Mark as read