Word Break - Part 2 | Practice | GeeksforGeeks

Given a string s and a dictionary of words dict of length n, add spaces in s to construct a sentence where each word is a valid dictionary word. Each dictionary word can be used more than once. Return all such possible sentences.
Follow examples for better understanding.
Example 1:
Input: s = "catsanddog", n = 5 
dict = {"cats", "cat", "and", "sand", "dog"}
Output: (cats and dog)(cat sand dog)
Explanation: All the words in the given 
sentences are present in the dictionary.
Example 2:
Input: s = "catsandog", n = 5
dict = {"cats", "cat", "and", "sand", "dog"}
Output: Empty
Explanation: There is no possible breaking 
of the string s where all the words are present 
in dict.
Your Task:
You do not need to read input or print anything. Your task is to complete the function wordBreak() which takes n, dict and s as input parameters and returns a list of possible sentences. If no sentence is possible it returns an empty list.
Expected Time Complexity: O(N2*n) where N = |s|
Expected Auxiliary Space: O(N2)
Constraints:
1 ≤ n ≤ 20
1 ≤ dict[i] ≤ 15
1 ≤ |s| ≤ 500 
0
pranavkhandare45451 week ago
//simple java code 
static List<String> wordBreak(int n, List<String> dict, String s)   {       // code here         List<String> list = new ArrayList<>();       helper(list, s, dict, new StringBuilder());                  return list;       }   static void helper(List<String> list, String s, List<String> dict, StringBuilder str){                   if(s.length() == 0){           str.deleteCharAt(str.length()-1);           list.add(str.toString());
           return;       }              for(int i = 0; i <= s.length(); i++){           String sub = s.substring(0,i);                     int l = str.length();           if(dict.contains(sub)){                          str.append(sub+ " ");               helper(list, s.substring(i), dict, str);               str.delete(l, str.length());           }       }
0
phenomenal11 week ago
JAVA Solution:
class Solution{
    static List<String> wordBreak(int n, List<String> dict, String s)
    {
        List<String> ans = new ArrayList<>();
        String res="";
        solve(s,dict,res,ans);
        
        return ans;
    }
    
    static void solve(String s,List<String> dict,String res,List<String> ans)
    {
        
        if(s.length()==0)
        {
            res=res.trim();
            ans.add(res);
            return;
        }
        
        for(int i=0;i<s.length();i++)
        {
            if(dict.contains(s.substring(0,i+1)))
            {
                solve(s.substring(i+1),dict,res+s.substring(0,i+1)+" ",ans);
            }
        }
    }
}
0
sandeep55212 weeks ago
C++ (DP+Backtracking) Solution (Time taken 0.01)
bool func(string &s,int b,int n, unordered_set<string> &us,string &a,vector<string> &ans,vector<int> &dp){
       if(b==n){
           a.pop_back();
           ans.push_back(a);
           return true;
       }
       if(dp[b]!=-1 and !dp[b]) return dp[b];
       string t,p;
       p=a;
       int flag=1;
       for(int i=b;i<n;i++){
           t.push_back(s[i]);
           if(us.find(t)==us.end()) continue;
           a+=t;a+=" ";
           if(func(s,i+1,n,us,a,ans,dp)) flag=0;
           a=p; // backtracking
       }
       if(flag) return dp[b]=false;
       return dp[b]=true;
   }
   vector<string> wordBreak(int n, vector<string>& wordDict, string &s)
   {
       // code here
       unordered_set<string> us;
       string a;
       vector<string> ans;
       n=s.size();
       vector<int> dp(n,-1);
       for(auto i:wordDict) us.insert(i);
       func(s,0,n,us,a,ans,dp);
       return ans;
   }
0
shilsoumyadip2 weeks ago
class Solution{public:  vector<string> v;void solve ( int i , vector<string> dict, string s, string temp){                string sum = "";        for (int j=i; j< s.length(); j++)        {            sum+= s[j];if (find(dict.begin(), dict.end(), sum) != dict.end()){       solve( j+1 , dict, s, temp+sum+" ");                  }          }            if (i >= s.length()){              temp.pop_back();              v.push_back (temp);            }    }   vector<string> wordBreak(int n, vector<string>& dict, string s)   {       solve( 0 , dict, s,"");       return v;           } };
0
gaurabhkumarjha271020014 weeks ago
// in c++
 vector<string> v;
 void solve (vector<string> dict, string s, string temp, int i){
         
          if (i >= s.length()){
               temp.pop_back();
               v.push_back (temp);
             }
          
           string str;
         for (int j=i; j< s.length(); j++){
             str+= s[j];
 if (find(dict.begin(), dict.end(), str) != dict.end()){
        solve(dict, s, temp+str+' ', j+1);
               }
           }
     }
    vector<string> wordBreak(int n, vector<string>& dict, string s)
    {
        solve(dict, s, "", 0);
        return v;
         
    } 
0
harrypotter01 month ago
## Word Break -2 def helper(n, curr, ans, dict,s ,n1):   if len(s)==0:       x = curr[:len(curr)-1]       ans.add(x)       return   for i in range(n1+1):       left = s[:i]       if left in dict:           right = s[i:]           curr = curr + (s[:i]+" ")           helper(n, curr, ans, dict, right, n1)           curr = curr[::-1].replace(str(s[:i]+" ")[::-1], "",1)[::-1]   return ans                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
class Solution:   def wordBreak(self, n, dict, s):       ans = helper(n, "", set(), dict, s, len(s))       return list(ans)                                                                                  
0
parikhsharan61 month ago
// Java solution 0.3s
 
class Solution{   private static List<String> words = null;      static List<String> wordBreak(int n, List<String> dict, String s)   {       words = new ArrayList<>();       wordBreak(n, dict, s, "");       return words;   }      private static void wordBreak(int n, List<String> dict, String s, String word) {              if(s.length() <= 0) {           words.add(word.trim());           return;       }              for(int i = 1; i <= s.length(); i++) {           String temp = s.substring(0, i);                      if(dict.contains(temp)) {               if(i == s.length()) {                   wordBreak(n, dict, "", word + " " + temp);               }               else {                   wordBreak(n, dict, s.substring(i, s.length()), word + " " + temp);                  }           }       }   }}
 
0
blank551k2 months ago
    static void word(ArrayList<String> a, ArrayList<String> dict, String s, String curr, int i){
       if(i>=s.length()){
           if(dict.contains(curr)){
               // s = "(" + s + ")";
               a.add(s);
           }
           return ;
       }
       if(dict.contains(curr)){
           String temp=s.substring(0,i)+" "+s.substring(i);
           word(a,dict,temp,""+s.charAt(i),i+2);
       }
       word(a,dict,s,curr+s.charAt(i),i+1);
   }
   
   static List<String> wordBreak(int n, List<String> mydict, String s)
   {
       ArrayList<String> dict= new ArrayList<String>(mydict);
       ArrayList<String> a = new ArrayList<String>();
       word(a,dict,s,"",0);
       return a;
       
   }
+1
aloksinghbais022 months ago
C++ solution using backtracking is as follows :- 
 
Execution Time :- 0.0 / 1.1 sec
 
unordered_map<string,bool> mp;      vector<string> helper(string str,int i,int j){       vector<string> ans;              string temp = str.substr(i,j-i+1);       if(mp[temp]) ans.push_back(temp);              for(int k = i; k < j; k++){           string left = str.substr(i,k-i+1);           if(mp[left]){               vector<string> v = helper(str,k+1,j);               for(auto right: v){                   ans.push_back(left + " " + right);               }           }       }              return (ans);   }      vector<string> wordBreak(int n, vector<string>& dict, string s){       for(auto str: dict){           mp[str] = true;       }       return helper(s,0,s.length()-1);   }
+1
choudharymanojloul8442 months ago
public:vector<string> ans;
   map<string,int>mp; 
  void solve(string &s,string &v,int pos)
  {
      if(pos==s.size())
      {
          v.pop_back();
          ans.push_back(v);
          return;
      }
      
      string temp="";
      for(int i=pos;i<s.size();++i)
      {
          temp+=s[i];
          if(mp.find(s.substr(pos,i-pos+1))!=mp.end())
          {
              string p=v+temp+" ";
              solve(s,p,i+1);
             
          }
      }
  }
    vector<string> wordBreak(int n, vector<string>& dict, string s)
    {
        // code here
        for(int i=0;i<n;++i)
        mp[dict[i]]++;
        string str;
        solve(s,str,0);
       // cout<<endl;
        return ans;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.