Tutorialspoint
Problem
Solution
Submissions

Word Break II

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program that returns all possible sentences where each word is a valid dictionary word, given a string and a dictionary of words. The same word in the dictionary may be reused multiple times in the segmentation.

Example 1
  • Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
  • Output: ["cats and dog","cat sand dog"]
  • Explanation:
    We have to break "catsanddog" using dictionary words.
    First possibility: "cats" + "and" + "dog" = "cats and dog".
    Second possibility: "cat" + "sand" + "dog" = "cat sand dog".
    Both combinations use only dictionary words.
Example 2
  • Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
  • Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
  • Explanation:
    Multiple ways to break the string using dictionary words.
    "pine" + "apple" + "pen" + "apple", "pineapple" + "pen" + "apple", "pine" + "applepen" + "apple".
Constraints
  • 1 ≤ s.length ≤ 20
  • 1 ≤ wordDict.length ≤ 1000
  • 1 ≤ wordDict[i].length ≤ 10
  • s and wordDict[i] consist of only lowercase English letters
  • Time Complexity: O(2^n) in worst case
  • Space Complexity: O(2^n) for storing results
StringsDynamic Programming PwCArctwist
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming with memoization to avoid recomputing subproblems
  • For each position in string, try all possible word matches from dictionary
  • If a word matches, recursively solve for the remaining substring
  • Use backtracking to build all possible sentence combinations
  • Memoize results for each starting position to optimize performance
  • Base case: empty string returns empty list indicating successful word break

Steps to solve by this approach:

 Step 1: Initialize memoization arrays to store computed results for each starting position.

 Step 2: Use recursive helper function that tries to break string from current starting position.
 Step 3: For each position, try all possible prefixes that match dictionary words.
 Step 4: If a prefix matches, recursively solve for the remaining substring after the prefix.
 Step 5: Combine current prefix with all possible suffixes to form complete sentences.
 Step 6: Store results in memoization array to avoid recomputing same subproblems.
 Step 7: Return all valid sentence combinations that use only dictionary words.

Submitted Code :