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.
Explanation
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n²) where n is the length of the input string s. We use nested loops to check all possible substrings.
Space Complexity: O(n + m) where n is the length of the input string s and m is the length of wordDict. This includes the dp array and the additional space used to create wordSet from wordDict.
Solution
Alternative Solution
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n * m) where n is the length of the input string s and m is the length of wordDict. We iterate through the string and check against each word in the dictionary.
Space Complexity: O(n) where n is the length of the input string s for the dp array.
Your account is free and you can post anonymously if you choose.