Member-only story
Word Break | Dynamic Programming | 1D
5 min readAug 15, 2023
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 the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Brute Force, Recursive approach
Time complexity is O(n^m), which represents the worst-case scenario when the function has to consider all possible combinations of words to form the input string.
Let’s understand recursive approach,
- It breaks the given string
- At each step, we check if we can find a dictionary word that matches the substring. If yes, we move to the next substring and repeat the process until we reach the end of the…