InterviewHubPRO
Section Overview
Q96

Question 96 of 100

Part 11: Dynamic Programming & Knapsack (91 - 100)

96%
DSA Patterns (Multi-Lang)•Part 11: Dynamic Programming & Knapsack (91 - 100)

Word Break.

In Simple Words: 1D DP array of size $N + 1$ initialized to false, with dp[N] = true. For each index $i$ working backwards, if wordDict contains s[i : i + len(w)] and dp[i + len(w)] is true, set dp[i] = true.

  • Time: $O(N \cdot M \cdot K)$ | Space: $O(N)$
Multi-Language Solutions
Switch tabs or choose All
def wordBreak(s: str, wordDict: list[str]) -> bool:
    dp = [False] * (len(s) + 1)
    dp[len(s)] = True
    for i in range(len(s) - 1, -1, -1):
        for w in wordDict:
            if (i + len(w)) <= len(s) and s[i : i + len(w)] == w:
                dp[i] = dp[i + len(w)]
            if dp[i]:
                break
    return dp[0]