← Back to Leo Academy Masterclass

Problem #139: Word Break

Medium Dynamic Programming

Intuition & Strategy Breakdown

Use 1D dynamic programming where dp[i] is true if s[:i] can be segmented into dictionary words. Check dp[j] and s[j:i] in dict.

Python Solution

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        word_set = set(wordDict)
        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 word_set:
                    dp[i] = True
                    break
        
        return dp[len(s)]

Java Solution

class Solution {
    public boolean wordBreak(String s, List wordDict) {
        Set wordSet = new HashSet<>(wordDict);
        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] && wordSet.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        
        return dp[s.length()];
    }
}
Watch Interactive Video on Leo Academy Main App