Tutorialspoint
Problem
Solution
Submissions

Word Break Problem

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Implement a function `wordBreak(s, wordDict)` that determines if a string `s` can be segmented into a space-separated sequence of one or more dictionary words. The same word in the dictionary may be reused multiple times in the segmentation. Return `True` if possible, otherwise `False`.

Example 1
  • Input: s = "Tutorialspoint" wordDict = ["Tutorials","point"]
  • Output: True
  • Explanation:
    • Step 1: Take the input string "Tutorialspoint".
    • Step 2: Check if it can be segmented using words from wordDict.
    • Step 3: The string can be divided into "Tutorials" and "point".
    • Step 4: Both "Tutorials" and "point" are in wordDict.
    • Step 5: Therefore, return True as "Tutorialspoint" can be segmented as"Tutorials point".
Example 2
  • Input: s = "applepenapple" wordDict = ["apple", "pen"]
  • Output: True
  • Explanation:
    • Step 1: Take the input string "applepenapple".
    • Step 2: Check if it can be segmented using words from wordDict.
    • Step 3: The string can be divided into "apple", "pen", and "apple".
    • Step 4: All these segments are in wordDict.
    • Step 5: Note that the same word "apple" is used twice in the segmentation.
    • Step 6: Therefore, return True as "applepenapple" can be segmented as "apple pen apple".
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
  • Time Complexity: O(n²) where n is the length of string s
  • Space Complexity: O(n)
ArraysDynamic Programming HCL TechnologiesZomato
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

  • Consider using dynamic programming to avoid redundant calculations
  • Use a boolean array dp[i] to indicate whether s[0...i-1] can be segmented
  • For each position i, check if any previous position j makes dp[j] true and s[j...i-1] is in the wordDict
  • Memoization can significantly improve performance for recursive approaches
  • Consider using a trie data structure for efficient word lookup

Steps to solve by this approach:

 Step 1: Convert the word dictionary to a set for O(1) lookups

 Step 2: Create a dynamic programming array dp[] where dp[i] represents whether s[0:i] can be segmented
 Step 3: Initialize dp[0] = True since an empty string can always be segmented
 Step 4: For each position i, check all previous positions j where dp[j] is true
 Step 5: If dp[j] is true and s[j:i] is in wordDict, set dp[i] to true and continue to the next i

Submitted Code :