![]() |
VOOZH | about |
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:
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.