Word Break
The problem
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words otherwise return false.
Note : The same word in dictionary can be used multiple times in segmentation.
Input : s = "takeuforward" , wordDict = ["take" , "forward" , "you", "u"] Output : true Explanation : Return true because "takeuforward" can be segmented as "take" , "u" , "forward".
Input : s = "applepineapple" , wordDict = ["apple"] Output : false Explanation : Return false because "applepineapple" can be segmented as "apple" , "pine" , "apple" but here we do not have "pine" word in dictionary.
Input : s = "catsanddogs" , wordDict = ["and" , "dogs" ,"cats", "animals"]
- 1 <= s.length <= 300
- 1 <= wordDict.length <= 1000
- 1 <= wordDict[i].length <= 20
- s and wordDict[i] consist only of English lowercase letters.
- All strings in wordDict are unique.
cpp
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
// Your code goes here
}
};java
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
// Your code goes here
}
}python
class Solution:
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
# Your code goes herejavascript
class Solution {
wordBreak(s, wordDict) {
// Your code goes here
}
}csharp
class Solution {
public bool WordBreak(string s, List<string> wordDict) {
}
}go
func wordBreak(s string, wordDict []string) bool {
}Stuck? Show a way to structure it+
- 01Put dictionary words in a hash set.
- 02Let dp[i] mean prefix s[0..i) is segmentable.
- 03For each reachable prefix, try valid next word endings.
- 04Return dp[n] and explain repeated-word allowance.
Reference answer
Then expect these follow-ups
How does a trie change the transitions?
Tests: tries
Why can greedy matching fail?
Tests: counterexamples
Hiring now
ServiceNow has 794 open roles right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Senior Software Engineer, Search Infrastructure - Moveworks
Mountain View, CALIFORNIA, United States
Staff Software Engineer, AI Native Engineering, Integrations
Hyderabad, India
Software Engineer
Santa Clara, CALIFORNIA, United States
Next question