Word Break | Practice | GeeksforGeeks

Given a string A and a dictionary of n words B, find out if A can be segmented into a space-separated sequence of dictionary words.
Note: From the dictionary B each word can be taken any number of times and in any order.
Example 1:
Input:
n = 12
B = { "i", "like", "sam",
"sung", "samsung", "mobile",
"ice","cream", "icecream",
"man", "go", "mango" }
A = "ilike"
Output:
1
Explanation:
The string can be segmented as "i like".


Example 2:
Input:
n = 12
B = { "i", "like", "sam",
"sung", "samsung", "mobile",
"ice","cream", "icecream", 
"man", "go", "mango" }
A = "ilikesamsung"
Output:
1
Explanation:
The string can be segmented as 
"i like samsung" or "i like sam sung".

 
Your Task:
Complete wordBreak() function which takes a string and list of strings as a parameter and returns 1 if it is possible to break words, else return 0. You don't need to read any input or print any output, it is done by driver code.

Expected time complexity: O(s2)
Expected auxiliary space: O(s) , where s = length of string A
 
Constraints:
1 ≤ N ≤ 12
1 ≤ s ≤ 1100 , where s = length of string A
 The length of each word is less than 15.
+2
guptatushar110411 day ago
unordered_set<string>st;
 
   int dp[1101];   int solve(string &s,int index)   {       if(index==s.size())return 1;       string temp;       if(dp[index]!=-1)           return dp[index];       for(int j=index;j<s.size();j++)       {        temp +=s[j];           if(st.find(temp)!=st.end())               if(solve(s,j+1))                   return dp[index]=1;       }       return dp[index]=0;   }   int wordBreak(string s, vector<string> &wordDict) {       //code here        memset(dp,-1,sizeof(dp));       for(auto x:wordDict)       {           st.insert(x);       }      return solve(s,0);    }
0
jainmuskan5652 weeks ago
unordered_map<string,int> mp;   int solve(string a, vector<string> &b){       int sz= a.length();       if(sz==0){           // size os 0 then we found out word           return 1;       }       if(mp[a]!= 0){           return mp[a];       }       for(int i=1;i<=sz;i++){           string subs= a.substr(0,i);           // compare the substrings with the b            int f=0;           // initialize a counter           for(int j=0;j<b.size();j++){               if(subs.compare(b[j])==0){                   f=1;                   break;                   // found a substring from a in b{} then break               }           }           if(f==1 && solve(a.substr(i,sz-i),b)==1){               return mp[a]=1;           }       }       return mp[a]=-1;   }   int wordBreak(string A, vector<string> &B) {              int z= solve(A,B);       if(z==1){           return 1;       }       return 0;   }
0
sandeep55213 weeks ago
C++ Tabulation DP Solution
int wordBreak(string &s, vector<string> &wordDict) {
       //code here
       unordered_set<string> us;
       for(auto i: wordDict) us.insert(i);
       int n=s.size(),flag;
       vector<int> dp(n+1,1);
       for(int i=n-1;i>=0;i--){
           string t;flag=1;
           for(int j=i;j<n;j++){
               t.push_back(s[j]);
               if(us.find(t)==us.end()) continue;
               if(dp[j+1]) flag--;
               if(!flag) break;
           }
           if(flag) dp[i]=0;
       }
       return dp[0];
   }
0
sougataroy8933 weeks ago
c++ sol
int fun(string &a,vector<string> &b){              if(s[a]) return 1;       for(int i=0;i<=a.size();i++){           string s1=a.substr(0,i);           string s2=a.substr(i);           if(s[s1] && (s[s2] || fun(s2,b))){               return 1;           }       }       return 0;   }   int wordBreak(string A, vector<string> &B) {       for(auto i: B){           s[i]++;       }       return fun(A,B);   }
+1
kshitij14103 weeks ago
bool isExist(string temp,vector<string> &b)   {              for(int i=0;i<b.size();i++)       {           if(b[i]==temp)           return true;       }              return false;   }   int flag=0;      bool solve(string str, vector<string>&s1,int k, int j)   {       for(int i=k;i<j;i++)       {           string temp=str.substr(k,i-k+1);                      //if it is exist           if(isExist(temp,s1))           {                              if(i+1==j)               {                   flag=1;                   return true;               }                              else{                   solve(str,s1,i+1,j);               }           }                  }       if(flag==1) return true;       return false;   }   int wordBreak(string A, vector<string> &B) {      int n=A.size();      return solve(A,B,0,n);   }};
+1
mukulbansal4214 weeks ago

class Sol
{
    public static int wordBreak(String s, ArrayList<String> b )
    {
        //code here
        int[] dp=new int[s.length()];
        for(int i=0;i<dp.length;i++){
            for(int j=0;j<=i;j++){
                String word=s.substring(j,i+1);
                if(b.contains(word))
                {
                    dp[i]+=1;
                }
            }
        }
        return dp[s.length()-1]>0?1:0;
    }
}
0
jmanm1 month ago
Recursive Java Solution:
 
public static int wordBreak(String A, ArrayList<String> B )   {       if (B.contains(A))           return 1;              if (rec(A, B, 1))           return 1;       else           return 0;   }      public static boolean rec(String A, ArrayList<String> B, int index) {       if (index == A.length())           return false;              String prefix = A.substring(0, index);       String suffix = A.substring(index, A.length());       if (B.contains(prefix) && B.contains(suffix))           return true;       else if (B.contains(prefix) && !B.contains(suffix))           return rec(suffix, B, 1) || rec(A, B, index+1);       else           return rec(A, B, index+1);   }
0
iamalizaidi1101 month ago
class Sol
{
    
    public static int wordBreak(String A, ArrayList<String> B )
    {
        if(solve(A,0,A.length(),B))
        return 1;
        else return 0;
        
    }
    public static boolean solve(String A,int i,int j,ArrayList<String> B)
    {
        if(i>=j)
        return false;
        if(B.indexOf(A.substring(i,j))!=-1)
        return true;
        
        for(int k=i;k<j-1;k++)
        {
            if(B.contains(A.substring(i,k+1)) && solve(A,k+1,j,B))
            return true;
        }
        return false;
    }
    
}
0
siddharthverma7971 month ago
class Sol{   public static int wordBreak(String A, ArrayList<String> B )   {       int dp[]=new int[A.length()];       for(int i=0;i<A.length();i++){           for(int j=0;j<=i;j++){               if(B.contains(A.substring(j,i+1))){                   dp[i]+=j>0?dp[j-1]:1;               }           }       }       return dp[A.length()-1];   }}
-1
mithileshkumarsingh1 month ago
  int i, j, k, n = B.size();
        set<string> mp;
        for (i = 0; i < n; i++) {
            mp.insert(B[i]);
        }
        int len = (int)A.size();
        vector<bool> dp(len + 1, false);
        dp[0] = true;
        for (int i = 1; i <= len; i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (dp[j] && mp.find(A.substr(j, i - j)) != mp.end()) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[len];
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.