Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"] Output: ["cats and dog","cat sand dog"]
Example 2:
Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"] Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"] Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: []
Constraints:
1 <= s.length <= 201 <= wordDict.length <= 10001 <= wordDict[i].length <= 10s and wordDict[i] consist of only lowercase English letters.wordDict are unique.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are given a long string of letters and a dictionary of valid words, and your job is to find every possible way to put spaces in that string so that every resulting piece is a valid word. The brute force strategy is to test every single place you could possibly insert a space and explore all resulting paths.
Here's how the algorithm would work step-by-step:
class Solution:
def wordBreak(self, string_to_break: str, word_dictionary: list) -> list:
dictionary_set = set(word_dictionary)
def backtrack(current_index: int) -> list:
# Base case: reaching the end of the string means we found a valid sentence path
if current_index == len(string_to_break):
return [""]
valid_sentences = []
for next_index in range(current_index + 1, len(string_to_break) + 1):
current_word = string_to_break[current_index:next_index]
# Only explore further if the prefix forms a valid word to prune dead ends
if current_word in dictionary_set:
remaining_sentences = backtrack(next_index)
for sentence in remaining_sentences:
if sentence:
valid_sentences.append(current_word + " " + sentence)
else:
valid_sentences.append(current_word)
return valid_sentences
return backtrack(0)To solve this puzzle efficiently, we can build the sentences from left to right by matching words from our dictionary to the beginning of the remaining text. To avoid doing the same exhausting work multiple times, we remember the valid sentence endings we have already discovered for any given piece of the text.
Here's how the algorithm would work step-by-step:
class Solution:
def wordBreak(self, input_string: str, word_dictionary: list[str]) -> list[str]:
dictionary_set = set(word_dictionary)
memoization_cache = {}
def backtrack(remaining_text):
# Memoization prevents redundant work by reusing previously computed valid sentences.
if remaining_text in memoization_cache:
return memoization_cache[remaining_text]
if not remaining_text:
return [""]
valid_sentences = []
for index_limit in range(1, len(remaining_text) + 1):
prefix_word = remaining_text[:index_limit]
# Matching prefixes against the dictionary allows us to build valid sentences from left to right.
if prefix_word in dictionary_set:
leftover_text = remaining_text[index_limit:]
subsequent_sentences = backtrack(leftover_text)
for sentence in subsequent_sentences:
if sentence:
complete_sentence = prefix_word + " " + sentence
else:
complete_sentence = prefix_word
valid_sentences.append(complete_sentence)
memoization_cache[remaining_text] = valid_sentences
return valid_sentences
return backtrack(input_string)| Case | How to Handle |
|---|---|
| String s cannot be segmented into any valid dictionary words | Return an empty list because the recursive backtracking explores all paths and finds no valid combinations. |
| Word dictionary contains duplicate strings | Use a hash set to store the dictionary for O(1) lookups and eliminate duplicate entries during initialization. |
| String s is extremely long or has exponential valid sentence combinations | Apply memoization to cache previously computed valid sentence suffixes to avoid redundant overlapping recursive calls. |
| String s equals a single word that is present in the dictionary | Return a list containing just the single word string without any added spaces. |
| Dictionary words are completely disjoint from the characters in string s | The base case checks will fail early on prefix matching and immediately return an empty list. |
| Dictionary contains words that are prefixes of other words in the dictionary | Explore all valid branching paths via backtracking so that both shorter and longer valid word splits are discovered. |
| Input string s is empty | Handle this edge case by returning an empty list or a list containing an empty string depending on the base case definition. |