Word break

Decide whether a string can be split into a sequence of words taken from a dictionary.

Time O(n²)Space O(n)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

dp[i] means the first i characters of s can be built from dictionary words. To fill it, try every earlier cut point j: if dp[j] is already true and the piece between j and i is a dictionary word, then dp[i] is true too.

Code

public static bool WordBreak(string s, HashSet<string> dict) {
    var dp = new bool[s.Length + 1];
    dp[0] = true;
    for (int i = 1; i <= s.Length; i++)
        for (int j = 0; j < i; j++)
            if (dp[j] && dict.Contains(s.Substring(j, i - j))) {
                dp[i] = true;
                break;
            }
    return dp[s.Length];
}
static boolean wordBreak(String s, Set<String> dict) {
    boolean[] dp = new boolean[s.length() + 1];
    dp[0] = true;
    for (int i = 1; i <= s.length(); i++)
        for (int j = 0; j < i; j++)
            if (dp[j] && dict.contains(s.substring(j, i))) {
                dp[i] = true;
                break;
            }
    return dp[s.length()];
}
bool wordBreak(const string& s, const unordered_set<string>& dict) {
    vector<bool> dp(s.size() + 1, false);
    dp[0] = true;
    for (int i = 1; i <= (int)s.size(); i++)
        for (int j = 0; j < i; j++)
            if (dp[j] && dict.count(s.substr(j, i - j))) {
                dp[i] = true;
                break;
            }
    return dp[s.size()];
}
def word_break(s: str, words: set[str]) -> bool:
    dp = [False] * (len(s) + 1)
    dp[0] = True
    for i in range(1, len(s) + 1):
        for j in range(i):
            if dp[j] and s[j:i] in words:
                dp[i] = True
                break
    return dp[len(s)]

Tips

In the .NET library

This counts whether a split exists, not the split itself. Recovering the actual words means also storing, for each true dp[i], which j made it true, then walking that chain backwards.