Taro Logo

Word Break II

#2 Most AskedHard
0 views
Topics:
StringsDynamic ProgrammingRecursion

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 <= 20
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 10
  • s and wordDict[i] consist of only lowercase English letters.
  • All the strings of wordDict are unique.
  • Input is generated in a way that the length of the answer doesn't exceed 105.

Solution


Clarifying Questions

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:

  1. What should we return if the string `s` cannot be segmented using the words in `wordDict`?
  2. Are there any constraints on the length of the string `s` and the size and length of words in `wordDict`?
  3. Can the words in `wordDict` be reused multiple times in the segmentation?
  4. Does `wordDict` contain duplicate words, and if so, should we treat them as distinct or unique during generation?
  5. Does the order of the sentences in the returned list matter?

Brute Force Solution

Approach

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:

  1. Begin at the very start of the letter string and look at the first few letters.
  2. Check if those first few letters match any word in your dictionary.
  3. If they form a valid word, imagine placing a space after them, leaving the rest of the string to be solved.
  4. Now, repeat the exact same process for the remaining part of the string, checking every possible stopping point for the next word.
  5. Whenever you successfully reach the end of the string, you have found a complete sentence of valid words, so save this combination as a successful result.
  6. If at any point the remaining letters do not match any word in your dictionary, stop exploring that path because it is a dead end.
  7. Continue this process of trying every single combination of splits until every possible path through the string has been fully explored and recorded.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(2^n) – The time complexity is driven by the recursive exploration of every possible space placement across the string of length n, where each position can either have a space or not. Because a string of length n has n-1 potential split points, there are 2^(n-1) possible combinations of splits to evaluate. In the worst-case scenario where every prefix forms a valid word and all paths lead to valid sentences, the algorithm generates and stores an exponential number of valid strings. This branching recursion explores up to 2^n paths, which simplifies to an overall time complexity of O(2^n).
Space Complexity
O(2^N + N) – The auxiliary space is driven by the recursion stack reaching a maximum depth of N, where N is the length of the string, and the exponential number of valid sentences stored in the result list. In the worst-case scenario, every prefix is a valid word, creating an exponential number of successful paths that must be recorded in memory. The intermediate path collections further contribute to memory during traversal before final accumulation. Consequently, the overall extra memory complexity is dominated by the storage of all valid sentence combinations, which grows exponentially with the input size N.

Optimal Solution

Approach

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:

  1. Look at the main string of letters and check if the very beginning matches any word in our provided dictionary.
  2. If a match is found, peel off that matching word and focus your attention on the leftover letters that remain.
  3. Repeat the process on the leftover letters by seeing if any dictionary word matches their beginning.
  4. If you ever reach the very end of the string, that means you have successfully built a complete and valid sentence, so save this combination.
  5. Along the way, if you find yourself working on a piece of text you have already solved before, immediately reuse the saved answers for that piece instead of recalculating them from scratch.
  6. Combine all the saved sentences you successfully formed along your journey and present them as the final result.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(2^n) – Let n be the length of the string s. In the worst-case scenario, every prefix of the string can be a valid dictionary word, leading to multiple branching choices at each step reminiscent of a binary decision tree. Since memoization prevents redundant work across identical remaining substrings, the time complexity is bounded by the total number of unique valid partitions and the cost to construct the resulting sentences. This results in an exponential growth factor proportional to the number of possible sentence combinations, simplifying to O(2^n) in the worst-case.
Space Complexity
O(2^N + V) – The auxiliary space is driven by the recursion call stack, which reaches a maximum depth of N where N is the length of the string, and the memoization hash map that stores previously solved suffixes. Additionally, the output list accumulates all valid sentence combinations, which in the worst-case scenario can grow exponentially with respect to N depending on the dictionary matches. Therefore, the total extra memory combines the recursive depth, the memoization table, and the storage required for all V valid resulting sentences.

Edge Cases

String s cannot be segmented into any valid dictionary words
How to Handle:
Return an empty list because the recursive backtracking explores all paths and finds no valid combinations.
Word dictionary contains duplicate strings
How to Handle:
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
How to Handle:
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
How to Handle:
Return a list containing just the single word string without any added spaces.
Dictionary words are completely disjoint from the characters in string s
How to Handle:
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
How to Handle:
Explore all valid branching paths via backtracking so that both shorter and longer valid word splits are discovered.
Input string s is empty
How to Handle:
Handle this edge case by returning an empty list or a list containing an empty string depending on the base case definition.
0/5 completed