Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Word Break II in Python
The Word Break II problem involves breaking a string into valid dictionary words and returning all possible sentence combinations. Given a string and a dictionary of valid words, we need to find all ways to add spaces to form valid sentences.
For example, with string "appleraincoat" and dictionary ["app", "apple", "rain", "coat", "raincoat"], we can form: "apple rain coat" and "apple raincoat".
Algorithm Approach
We use dynamic programming with memoization to avoid redundant calculations ?
Create a memoization map to store results for substrings
For each position, check if the prefix exists in the dictionary
Recursively solve for the remaining substring
Combine results and cache them for future use
Implementation
class Solution:
def wordBreak(self, s, wordDict):
self.memo = {}
wordDict = set(wordDict) # Convert to set for O(1) lookup
return self.solve(s, wordDict)
def solve(self, s, wordDict):
# Base case: empty string returns empty sentence
if not s:
return ['']
# Check memoization
if s in self.memo:
return self.memo[s]
result = []
# Try all possible prefixes
for i in range(1, len(s) + 1):
prefix = s[:i]
if prefix in wordDict:
# Recursively solve for remaining string
suffixes = self.solve(s[i:], wordDict)
for suffix in suffixes:
# Combine prefix with suffix
sentence = (prefix + " " + suffix).strip()
result.append(sentence)
# Memoize result
self.memo[s] = result
return result
# Example usage
solution = Solution()
s = "appleraincoat"
wordDict = ["app", "apple", "rain", "coat", "raincoat"]
sentences = solution.wordBreak(s, wordDict)
for sentence in sentences:
print(f"'{sentence}'")
'apple rain coat' 'apple raincoat'
How It Works
The algorithm works by exploring all possible ways to break the string ?
Memoization: Store results for each substring to avoid recalculation
Prefix checking: For each position, check if the prefix is a valid word
Recursive breakdown: If prefix is valid, recursively solve for the remaining part
Result combination: Combine valid prefixes with all possible suffix combinations
Another Example
solution = Solution()
# Example with multiple valid combinations
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
result = solution.wordBreak(s, wordDict)
print("Input string:", s)
print("Dictionary:", wordDict)
print("All valid sentences:")
for sentence in result:
print(f" '{sentence}'")
Input string: catsanddog Dictionary: ['cat', 'cats', 'and', 'sand', 'dog'] All valid sentences: 'cats and dog' 'cat sand dog'
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(2^n) | Worst case when all substrings are valid words |
| Space | O(2^n) | Memoization storage and recursion stack |
Conclusion
The Word Break II problem uses dynamic programming with memoization to find all valid sentence combinations. The algorithm efficiently explores all possibilities while avoiding redundant calculations through caching.
