AAlgoLoopSpaced repetition for LeetCode
MEDIUMDynamic ProgrammingLeetCode ↗

Word Break

The key idea

Let dp[i] mean the prefix s[0:i] can be fully segmented into dictionary words. dp[0] is true (the empty prefix). For each end i, scan every split point j < i: if dp[j] is true and the chunk s[j:i] is in the dictionary, then dp[i] is reachable too. The answer is dp[n].

Problem

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Note that the same word in wordDict may be reused multiple times in the segmentation.

Constraints

Examples

Input: s = "leetcode", wordDict = ["leet","code"] Output: true
Input: s = "applepenapple", wordDict = ["apple","pen"] Output: true
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: false

Complexity

Time: O(n^2) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Dynamic Programming problems