Advertisement

Word Break II - LeetCode 140 Solution

Word Break II - Complete Solution Guide

Word Break II is LeetCode problem 140, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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

Detailed Explanation

The problem asks us to take a string `s` and a dictionary of words `wordDict`. The goal is to break the string `s` into a sequence of words, where each word is present in the `wordDict`. We need to return all possible ways to break the string into valid sentences, represented as a list of strings. The same word in `wordDict` can be reused multiple times. If no such segmentation is possible, we return an empty list.

Solution Approach

The provided solution uses a backtracking algorithm with memoization to find all possible word breaks. It explores the string recursively, attempting to match prefixes with words in the dictionary. Memoization is used to store the results of subproblems, preventing redundant computations and significantly improving performance. The base case is when the starting index reaches the end of the string, in which case an empty string is added to the result. The recursive step involves iterating through all possible ending indices to create candidate words. If a candidate word is in the dictionary, the algorithm recursively calls itself on the remaining part of the string, and combines the current word with the results of the recursive call to build valid sentences.

Step-by-Step Algorithm

  1. Step 1: Create a set `word_set` from the `wordDict` for efficient word lookups.
  2. Step 2: Initialize a memoization dictionary `memo` to store results of already computed subproblems where key is the start index and value is the list of possible sentences.
  3. Step 3: Define a recursive function `backtrack(start_index)` that takes the starting index of the substring as input.
  4. Step 4: Inside `backtrack`, check if the result for `start_index` is already memoized. If so, return the memoized value.
  5. Step 5: If `start_index` reaches the end of the string, return a list containing an empty string (representing the base case: no more characters to process).
  6. Step 6: Iterate from `start_index` to the end of the string, creating potential words (substrings).
  7. Step 7: For each potential word, check if it's present in `word_set`.
  8. Step 8: If the potential word is valid, recursively call `backtrack(end_index + 1)` to find all possible sentences for the remaining substring.
  9. Step 9: Combine the current word with each of the sentences returned by the recursive call, adding a space if the returned sentence is not empty. Add the combined sentences to the `results` list.
  10. Step 10: Store the computed `results` in the `memo` for `start_index` and return the `results` list.

Key Insights

  • Insight 1: Backtracking with memoization is essential to avoid redundant computations and handle the potentially large number of possible segmentations, making it computationally feasible.
  • Insight 2: The problem can be naturally solved using recursion, exploring all possible prefixes of the string and checking if they are valid words.
  • Insight 3: Using a set data structure for the word dictionary allows for efficient lookups (O(1) on average) when checking if a substring is a valid word.

Complexity Analysis

Time Complexity: O(2^n)

Space Complexity: O(n^3)

Topics

This problem involves: Array, Hash Table, String, Dynamic Programming, Backtracking, Trie, Memoization.

Companies

Asked at: Dropbox, Grammarly, Moveworks, Oracle, ServiceNow, Snap, TikTok, Uber, X.