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 
+1
arkoghoshdastidar3920006 days ago
C++ Solution :
 
class Solution{
public:
    bool presentInDict(vector<string> const    						&dict, int n, string s)
    {
        for(int i=0; i<n; i++)
        {
            if(dict[i] == s)
            {
                return true;
            }
        }
        return false;
    }
    
    void wordBreak(int n, vector<string> &dict, string s, string smallOutput, vector<string> &output)
    {
        if(s.size() == 0)
        {
            output.push_back(smallOutput);
            return;
        }
        string temp;
        for(int i=0; i<s.size(); i++)
        {
            temp += s[i];
            if(presentInDict(dict, n, temp))
            {
                if(!smallOutput.size())
                {
                    wordBreak(n, dict, s.substr(i+1), temp, output);
                }
                else
                {
                    wordBreak(n, dict, s.substr(i+1), smallOutput+" "+temp, output);
                }
            }
        }
    }
    
    vector<string> wordBreak(int n, vector<string>& dict, string s)
    {
        vector<string> output;
        string smallOutput;
        wordBreak(n, dict, s, smallOutput, output);
        return output;
    }
};
+2
abhishekfarswan1 week ago
Using BackTracking in C++
class Solution{   public:   vector<string> solution;      bool wordAvailable(string tmp,vector<string>& dict,int n){       for(int i=0;i<n;i++){           if(dict[i]==tmp){               return true;           }       }       return false;   }      void breakingWords(int n, vector<string>& dict,string s,int start,string sub){       if(start == s.length()){           solution.push_back(sub.substr(0,sub.length()-1));           return;       }       string tmp="";       for(int i=start;i<s.length();i++){           tmp+=s[i];           if(wordAvailable(tmp,dict,n)){               breakingWords(n,dict,s,i+1,sub+tmp+" ");           }       }   }      vector<string> wordBreak(int n, vector<string>& dict, string s)   {       breakingWords(n,dict,s,0,"");       return solution;   }};
0
wjyjobs1 week ago
    def wordBreak(self, n, dict, s):
        
        @lru_cache(None)
        def brk(s, i):
            ret = []
            if s[i:] in dict:
                ret.append(s[i:])
                
            for j in range(i+1, len(s)):
                if s[i:j] in dict:
                    r = brk(s, j)
                    for sentence in r:
                        ret.append(s[i:j] + " " + sentence)
            return ret
        
        return brk(s, 0)
0
disaster2 weeks ago
class Solution{
    vector<string> res;
    map<string, bool> hash;
public:
    void rec(int ind, string curr, string s, vector<string>& dict){
        if(ind == s.size())  res.push_back(curr);
        
        for(int i=ind;i<s.length();i++){
            string sub = s.substr(ind, i-ind+1);
            if(hash.find(sub) != hash.end()){
                string ne;
                if(curr == "")  ne = sub;
                else    ne = curr+" "+sub;
                rec(i+1, ne, s, dict);
            }
        }
    }
    vector<string> wordBreak(int n, vector<string>& dict, string s)
    {
        // code here
        for(auto word: dict)    hash[word] = true;
        rec(0, "", s, dict);     
        return res;
    }
};
+1
harsh63102 weeks ago
Easy and Short solution. ( 0.01s )
vector<string> getAns(string& s, unordered_set<string>& dict,unordered_map<string, vector<string>>& map){
    if(map.count(s))
        return map[s] ;
    
    vector<string> ans ;
    string back, front=s ;
    if(dict.find(front) != dict.end())
        ans.push_back(front) ;

    for(int i=(int)s.size()-1 ; i>=0 ; i--){
        front.pop_back() ;
        back = s[i]+back ;
        if(dict.find(back) == dict.end())
            continue ;
        vector<string> temp = getAns(front,dict,map) ;
        for(auto &str: temp)
            ans.push_back(str + " " + back) ;
    }
    
    return map[s] = ans ;
}

vector<string> wordBreak(int n, vector<string>& dict, string& s){
    unordered_map<string, vector<string>> map ;
    unordered_set<string> dic(dict.begin(), dict.end()) ;
    return getAns(s,dic,map) ;
}
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.