VOOZH about

URL: https://www.geeksforgeeks.org/dsa/word-break-problem-dp-32-set-2/

⇱ Word Break - Find All Ways to Break - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Word Break - Find All Ways to Break

Last Updated : 2 Mar, 2026

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

Examples:

Input: s = "likegfg" , dict[] = ["lik", "like", "egfg", "gfg"]
Output: "lik egfg", "like gfg"
Explanation: The string "likegfg" is segmented into valid dictionary words in all possible ways: "lik egfg" and "like gfg".

Input: s = "geeksforgeeks" , dict[] = ["for", "geeks"]
Output: "geeks for geeks" 
Explanation: The string "geeksforgeeks" can be broken into valid words from the dictionary in one ways.

[Naive Approach] Using Recursion - O((2^n) * k) Time and O(n) Space

In the recursive approach, we try to break the string starting from a given index by checking every possible substring from that position. If a substring is found in the dictionary, we recursively check whether the remaining part of the string can also be broken successfully. If we reach the end of the string, it means we were able to split the entire string into valid dictionary words, so we return true.

For implementation of the above recursive approach, please refer to Word Break Problem using Backtracking.

[Expected Approach 1] Using TopDown DP - O((n^2)*m) Time and O(n*m) Space

In the memoization approach, we solve the problem starting from a given index and store the result for that index in a map (memo). For each substring starting at start, if it exists in the dictionary, we recursively compute all valid sentence breaks from the next index (end). Before solving any index, we check if its result is already stored in memo to avoid recomputation. This ensures each starting index is processed only once, reducing overlapping subproblems.


Output
lik egfg
like gfg

[Expected Approach 2] Using BottomUp DP - O((n^2)*m) Time and O(n*m) Space

In the bottom-up DP approach, we create an array dp where dp[i] stores all valid sentences that can be formed starting from index i. We process the string from right to left, and for each index i, we check every substring s[i:j]. If the substring exists in the dictionary, we combine it with all valid sentences already stored in dp[j] and add the formed sentences to dp[i].



Output
lik egfg
like gfg
Comment
Article Tags:
Article Tags: