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.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: false
Constraints:
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20s and wordDict[i] consist of only lowercase English letters.wordDict are unique.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a long, glued-together string of letters and a dictionary of valid words. The brute force approach tries every conceivable way to chop the big string into smaller pieces to see if every single resulting piece matches a word in your dictionary.
Here's how the algorithm would work step-by-step:
def word_break(target_string, word_dictionary): dictionary_set = set(word_dictionary) def helper_function(start_index): if start_index == len(target_string): return True # Try all possible end points to find a valid prefix word in the remaining substring for current_end in range(start_index + 1, len(target_string) + 1): prefix_substring = target_string[start_index:current_end] if prefix_substring in dictionary_set: # Recursively check the rest of the string assuming the current prefix is valid if helper_function(current_end): return True # Backtrack if no valid combination of words can be formed from this starting point return False return helper_function(0)Instead of blindly trying every single combination of words, the optimal approach builds the solution progressively from left to right. It remembers the answers to smaller puzzle pieces along the way so it never has to solve the same sub-problem twice.
Here's how the algorithm would work step-by-step:
def word_break(secret_message, dictionary_words):
word_set = set(dictionary_words)
message_length = len(secret_message)
bookmark_table = [False] * (message_length + 1)
bookmark_table[0] = True
# Iterate through each starting position to check if a valid segment can be formed up to this point.
for current_position in range(message_length):
if not bookmark_table[current_position]:
continue
# Check all possible end positions ahead to see if the substring forms a valid dictionary word.
for next_position in range(current_position + 1, message_length + 1):
candidate_word = secret_message[current_position:next_position]
# If a valid word is found and the starting point was reachable, mark the end point as a successful bookmark.
if candidate_word in word_set:
bookmark_table[next_position] = True
return bookmark_table[message_length]| Case | How to Handle |
|---|---|
| Empty input string s | The DP table initializes the base case dp[0] as true, which correctly returns true for an empty string. |
| Empty word dictionary | Without any words, the algorithm cannot match any substrings, resulting in dp[0] remaining true and all subsequent indices false. |
| String s is shorter than any word in the dictionary | The inner loop checks word lengths, and since all dictionary words exceed s length, no matches are found and false is returned. |
| All dictionary words are single characters matching the string | The DP approach efficiently builds up matches character by character, correctly validating the full string length. |
| Repeated overlapping dictionary words | Using a set for the dictionary and a memoized DP table prevents redundant calculations and correctly handles overlapping segmentations. |
| Very long string s with no possible segmentation | An O(n^2) DP approach ensures the algorithm executes within time limits without causing recursion depth errors like pure DFS would. |
| Dictionary contains words that are prefixes of other words | Checking all possible substring lengths via nested loops ensures longer valid words are properly evaluated alongside their shorter prefixes. |
| String s cannot be segmented at all | The DP array values will remain false past the initial base case, causing the final return value to be false. |