VOOZH about

URL: https://www.geeksforgeeks.org/dsa/word-break-problem-using-backtracking/

⇱ Word Break Problem using Backtracking - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Word Break Problem using Backtracking

Last Updated : 25 Nov, 2024

Given a non-empty sequence s and a dictionary dict[] containing a list of non-empty words, the task is to return all possible ways to break the sentence in individual dictionary words.
Note: The same word in the dictionary may be reused multiple times while breaking.
Examples:

Input: s = “catsanddog” , dict = [“cat”, “cats”, “and”, “sand”, “dog”]
Output:
“cats and dog” 
“cat sand dog”
Explanation: The string is split into above 2 ways, in each way all are valid dictionary words.

Input: s = “pineapplepenapple” , dict = [“apple”, “pen”, “applepen”, “pine”, “pineapple”]
Output:
“pine apple pen apple” 
“pineapple pen apple” 
“pine applepen apple” 
Explanation: The string is split into above 3 ways, in each way all are valid dictionary words.

Approach:

For the recursive approach, there are two cases at each step (the size of the string decreases in each step):

  • Include the current substring in the solution, If the substring exists in the dictionary, recursively check for the rest of the string starting from the next index.
  • Skip the current substring and move to the next possible substring starting from the same index.

wordBreak(s,start) = wordBreak(s, end) , if s[start:end] ∈ dictionary

Base Case : wordBreak(s, start) = true, this signifies that a valid sentence has been constructed for the given input string.

Steps to implement the above idea:

  • Convert the dictionary into a hash set for quick search.
  • If the start index reaches the length of the string (s), it signifies a valid sentence has been constructed. Add the current sentence (curr) to the result.
  • Loop through everysubstring starting at start and ending at all possible positions (end).
  • For each substring, check if it exists in the dictionary (dictSet).
  • If valid:
    • Append the word to the current sentence (curr).
    • Recursively call the function for the remaining part of the string (from end onwards).
  • After the recursive call returns, restore the state of curr to ensure the next branch of exploration starts with the correct sentence.

Output
i like sam sung mobile
i like samsung mobile

Time Complexity: O((2^n) * k), for a string of length n, there are 2^n possible partitions, and each substring check takes O(k) time (average substring length k), leading to O((2^n) * k).
Auxiliary Space: O(n), due to the recursion stack can go as deep as O(n) in the worst case.

Comment
Article Tags:
Article Tags: