KatInterview

140. Word Break II

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to segment a given string s into a sequence of one or more dictionary words. We need to find all possible such segmentations. For example, if s = "catsanddog" and the dictionary is ["cat", "cats", "and", "sand", "dog"], the valid sentences are "cats and dog" and "cat sand dog". This problem can be solved by exploring all possible ways to break the string and checking if each part is a valid word. Since we are looking for all possibilities, this suggests a recursive or backtracking approach.

Solution

Word Break II in Python

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        wordSet = set(wordDict)
        memo = {}

        def dfs(current_s: str) -> List[str]:
            # If result for this substring is already computed, return it.
            if current_s in memo:
                return memo[current_s]

            # According to problem constraints, s is non-empty initially.
            # A recursive call might be on an empty string if a word matches
            # the whole current_s, but this is handled by the suffix check.
            # We can add an explicit check, but it's not strictly necessary for this logic.

            results = []
            # Iterate through all possible prefixes of the string.
            for i in range(1, len(current_s) + 1):
                prefix = current_s[:i]

                # If the prefix is a valid word.
                if prefix in wordSet:
                    suffix = current_s[i:]

                    # If there's no suffix, we have a complete sentence part.
                    if not suffix:
                        results.append(prefix)
                    else:
                        # Recurse on the suffix.
                        suffix_results = dfs(suffix)
                        # Combine prefix with each of the suffix results.
                        for sub_sentence in suffix_results:
                            results.append(prefix + " " + sub_sentence)
            
            # Memoize the result for the current substring and return.
            memo[current_s] = results
            return results

        return dfs(s)

Word Break II in Java

class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        // Use a Set for O(1) average time complexity word checks.
        Set<String> wordSet = new HashSet<>(wordDict);
        // Memoization map to store results for substrings.
        Map<String, List<String>> memo = new HashMap<>();
        return dfs(s, wordSet, memo);
    }

    private List<String> dfs(String s, Set<String> wordSet, Map<String, List<String>> memo) {
        // If result for this substring is already computed, return it.
        if (memo.containsKey(s)) {
            return memo.get(s);
        }

        List<String> results = new ArrayList<>();
        
        // Problem constraints state s.length() >= 1, so s is not empty on initial call.
        // Subproblem calls can have empty suffix, which is handled inside the loop.

        // Iterate through all possible prefixes of the string s.
        for (int i = 1; i <= s.length(); i++) {
            String prefix = s.substring(0, i);

            // If the prefix is a valid word in the dictionary.
            if (wordSet.contains(prefix)) {
                String suffix = s.substring(i);

                // If the suffix is empty, we found a valid sentence.
                if (suffix.isEmpty()) {
                    results.add(prefix);
                } else {
                    // Recursively call dfs for the suffix.
                    List<String> suffixResults = dfs(suffix, wordSet, memo);
                    // Append the current prefix to each of the suffix results.
                    for (String subSentence : suffixResults) {
                        results.add(prefix + " " + subSentence);
                    }
                }
            }
        }

        // Memoize the results for the current string s and return.
        memo.put(s, results);
        return results;
    }
}

Word Break II in C++

class Solution {
public:
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
        unordered_map<string, vector<string>> memo;
        return dfs(s, wordSet, memo);
    }

private:
    vector<string> dfs(const string& s, const unordered_set<string>& wordSet, unordered_map<string, vector<string>>& memo) {
        // If result for this substring is already computed, return it.
        if (memo.count(s)) {
            return memo.at(s);
        }

        vector<string> results;
        
        // The problem constraints say s.length() >= 1, so s is never empty here on initial call.
        // A subproblem call `dfs(suffix)` can have an empty suffix, handled inside the loop.

        // Iterate through all possible prefixes of the string s.
        for (int i = 1; i <= s.length(); ++i) {
            string prefix = s.substr(0, i);

            // If the prefix is a valid word in the dictionary.
            if (wordSet.count(prefix)) {
                string suffix = s.substr(i);

                // If the suffix is empty, it means we have found a valid sentence.
                if (suffix.empty()) {
                    results.push_back(prefix);
                } else {
                    // Recursively call dfs for the suffix.
                    vector<string> suffix_results = dfs(suffix, wordSet, memo);
                    // Append the current prefix to each of the suffix results.
                    for (const string& sub_sentence : suffix_results) {
                        results.push_back(prefix + " " + sub_sentence);
                    }
                }
            }
        }
        
        // Memoize the results for the current string s and return.
        memo[s] = results;
        return results;
    }
};

Word Break II in TypeScript

function wordBreak(s: string, wordDict: string[]): string[] {
    // Use a Set for O(1) average time complexity word checks.
    const wordSet = new Set(wordDict);
    // Memoization map to store results for substrings.
    const memo = new Map<string, string[]>();

    const dfs = (currentS: string): string[] => {
        // If result for this substring is already computed, return it.
        if (memo.has(currentS)) {
            return memo.get(currentS)!;
        }

        const results: string[] = [];

        // Iterate through all possible prefixes of the string.
        for (let i = 1; i <= currentS.length; i++) {
            const prefix = currentS.substring(0, i);

            // If the prefix is a valid word.
            if (wordSet.has(prefix)) {
                const suffix = currentS.substring(i);

                // If the suffix is empty, we found a valid sentence.
                if (suffix === "") {
                    results.push(prefix);
                } else {
                    // Recursively call dfs for the suffix.
                    const suffixResults = dfs(suffix);
                    // Append the current prefix to each of the suffix results.
                    for (const subSentence of suffixResults) {
                        results.push(prefix + " " + subSentence);
                    }
                }
            }
        }

        // Memoize the results for the current string and return.
        memo.set(currentS, results);
        return results;
    };

    return dfs(s);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.