Taro Logo

Word Break

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+25
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.5K views
Topics:
StringsDynamic Programming

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 <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and wordDict[i] consist of only lowercase English letters.
  • All the strings of wordDict are unique.

Solution


Clarifying Questions

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:

  1. What is the maximum length of the string `s` and the maximum number of words in `wordDict`?
  2. Are all characters in the string `s` and the dictionary words lowercase English letters?
  3. Can the `wordDict` contain duplicate words, and can `s` or `wordDict` be empty?
  4. Since we can reuse words from the dictionary multiple times, is there any upper limit on how many words can be chained together?
  5. Do we need to find all possible ways to segment the string, or is returning a boolean indicating whether *any* valid segmentation exists sufficient?

Brute Force Solution

Approach

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:

  1. Start at the very beginning of the full string of letters.
  2. Look ahead by one letter and check if that tiny piece matches any word in your dictionary.
  3. If it matches, consider that a valid first word, and then apply this exact same checking process to the remaining part of the string.
  4. If that first piece does not match a dictionary word, instead look ahead by two letters, then three letters, and keep expanding until you find a matching word at the start.
  5. Whenever you successfully find a matching word, temporarily pretend it is part of a valid sentence and try to solve the rest of the string in the same exhaustive way.
  6. If you ever reach a point where the remaining letters do not match any dictionary word and you have exhausted all previous choices, step back and try a different chopping point for the previous word.
  7. Keep trying every possible combination of cuts until you either successfully chop the entire string into valid dictionary words or run out of every single possibility.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(n^2 * m) – Let n be the length of the string and m be the maximum length of a word in the dictionary. For each of the n positions in the string, we examine all possible substrings starting at that index, which takes up to n steps. Slicing the string and checking it against the dictionary takes O(m) time per substring. This results in approximately n * n / 2 substring checks, each costing O(m) operations, which simplifies to O(n^2 * m).
Space Complexity
O(N) – To eliminate redundant computations described in the chopping and backtracking steps, the optimal solution utilizes a boolean DP array of size N plus one, where N represents the length of the input string. Additionally, the recursion stack or iterative loops consume constant auxiliary storage beyond this lookup array. Storing the dictionary words in a hash set scales with the number and length of the words, but the primary algorithmic auxiliary memory is dominated by the linear DP tracking table. Thus, the total auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

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:

  1. Imagine standing at the very beginning of the secret message and looking for the first valid dictionary word.
  2. Once you find a valid word, put a mental bookmark at that spot to remember that everything up to this point can be successfully formed.
  3. From your new bookmark, look further ahead into the remaining hidden message to find the next valid word.
  4. If you ever reach a point where no valid dictionary words can be formed from your current bookmark, you know that path is a dead end and you can stop exploring it.
  5. Continue this process of jumping from bookmark to bookmark, checking manageable chunks of the message rather than every possible letter combination.
  6. If your bookmarks successfully carry you all the way to the very end of the message, you know the entire puzzle can be solved.

Code Implementation

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]

Big(O) Analysis

Time Complexity
O(n^2 * m) – Let n be the length of the string and m be the maximum length of a word in the dictionary. The outer loop advances our bookmark through each of the n characters in the message. For every character position, an inner loop examines up to m previous bookmarks to test substrings of dictionary-check length. This creates approximately n * (m/2) substring operations, each taking up to O(m) time to hash or compare. Combining these steps yields roughly n^2 * m operations, which simplifies to O(n^2 * m).
Space Complexity
O(N) – The auxiliary space is driven by a boolean array that stores intermediate results for each prefix of the secret message. Because this tracking array has a length proportional to the string length N plus one, the memory grows linearly. Additionally, converting the dictionary into a hash set for fast lookups consumes extra memory proportional to the total number of characters in the dictionary, but the dominant auxiliary data structure scaling with the input string size N is the dynamic programming table.

Edge Cases

Empty input string s
How to Handle:
The DP table initializes the base case dp[0] as true, which correctly returns true for an empty string.
Empty word dictionary
How to Handle:
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
How to Handle:
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
How to Handle:
The DP approach efficiently builds up matches character by character, correctly validating the full string length.
Repeated overlapping dictionary words
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The DP array values will remain false past the initial base case, causing the final return value to be false.
0/75 completed