Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Word Break II

Hard
0/120
Average time to solve is 15m
profile
Contributed by
101 upvotes
Asked in companies
SalesforceTata Consultancy Services (TCS)Infosys

Problem statement

You are given a non-empty string S containing no spaces’ and a dictionary of non-empty strings (say the list of words). You are supposed to construct and return all possible sentences after adding spaces in the originally given string ‘S’, such that each word in a sentence exists in the given dictionary.

Note :

The same word in the dictionary can be used multiple times to make sentences.
Assume that the dictionary does not contain duplicate words.
Detailed explanation ( Input/output format, Notes, Images )

Input format :

The first line contains an integer ‘T’ denoting the number of test cases. 

Then the 'T' test cases follow.

The first line contains an integer value ‘K’ which denotes the size of the dictionary.

The second line contains ‘K’ non-empty, space separated strings denoting the words of the dictionary.

The third line contains a non-empty string ‘S’.

Output format :

For each test case, print each possible sentence after adding spaces, in different lines.

The output of each test case is printed in a separate line. 
Note :
1. You do not need to print anything, it has already been taken care of. Just implement the given function.
2. The order in which the output sentences are returned does not matter.
Constraints :
1 <= T <= 10
1 <= K <= 100
1 <= | word | <= 16
1 <= | S | <= 13

where |word| is the length of each word in the dictionary and |S| is the length of the string S.

Time Limit: 1 sec
Sample Input 1:
1
6
god is now no where here
godisnowherenowhere
Sample Output 1:
god is no where no where
god is no where now here
god is now here no where
god is now here now here
Explanation to Sample Input 1:
One way to make sentences is to take “god” and append a space, then take “is”  and append space, take “now” from the dictionary and take “here” as well. 
Similarly, for other sentences also, we can add space to get other possible sentences. Note that we can reuse dictionary words as “no” and “now” are used two times in the same sentence.
Sample Input 2:
1
4
god is no here
godisnowhere
Sample Output 2:
No output to be printed
Explanation to Sample Input 2:
We can not make any sentence because after making “god is no” we will be stuck with “where”. There is no way to break “where” further such that we can get any word from the dictionary.
Hint

Can you think about exploring all the possibilities?

Approaches (3)
Recursion

We need to keep exploring the given string from current position ‘i’ to until we wouldn’t find a position such that substring ‘i’ to ‘j’ exists in the dictionary.
 

Algorithm:

  • Store all words of the dictionary in a set to speed up the process of checking whether a current word exists in the dictionary or not.
  • Base condition, If we have checked for all the substrings, then just return with a list containing only a null string
  • Else,
    • Start exploring every substring from the start of the string and check if it is in the HashSet.
      • If it is present in the HashSet:
        • Check if it is possible to form the rest of the sentence using dictionary words. If yes, you append the current substring to all the substrings possible from the rest of the sentences.
    • If none of the substrings of sentences are present in the HashSet, then there are no sentences possible from the current string.
  • Return all the valid output sentences.
Time Complexity

O(N * (2 ^ (N - 1)), where ‘N’ is the length of the sentence.

For each space between 2 characters, we can either break the word there or not. Thus, the number of maximum word breaks is 2 ^ (N - 1) (because the string of length N will have N - 1 spaces between 2 characters).

And for a single option, we will have to put it into the list which will cost ‘N’. Thus, the final time complexity would be O(N * (2 ^ N)).

Space Complexity

O(N * (2 ^ (N - 1))), where ‘N’ is the length of the sentence.

In the worst case, we will have to store all possible combinations for all indexes to print the output. There are O(2 ^ (N - 1)) combinations of sentences and the length of the sentence will be somewhere between N and 2 * N. So, the overall space complexity will be O(N * (2 ^ (N - 1))).

Code Solution
(100% EXP penalty)
Word Break II
All tags
Sort by
Search icon

Interview problems

Easy recursion solution in java!!

import java.util.* ;
import java.io.*; 
import java.util.ArrayList;

public class Solution {

	public static void solve(String s, ArrayList<String> dictionary, ArrayList<String> ans ,String temp){
		// base case:
		if(s.length() == 0){
			temp.trim();
			ans.add(temp);
			return;
		}

		for( int i = 0; i<s.length(); i++){
			String left = s.substring(0,i+1);
			if(dictionary.contains(left)){
				solve(s.substring(i+1),dictionary,ans ,temp+left+" ");
			}
		}
	}
	public static ArrayList<String> wordBreak(String s, ArrayList<String> dictionary) {
		// Write your code here.
		ArrayList<String> ans = new ArrayList<String>();
		solve(s,dictionary,ans ,"");
		return ans;
	}
}
23 views
0 replies
0 upvotes

Interview problems

word break II solved in easy way

import java.util.* ;
import java.io.*; 
import java.util.ArrayList;

public class Solution {

	public static ArrayList<String> wordBreak(String s, ArrayList<String> dictionary) {
		// Write your code here.
		Set<String>hs = new HashSet<>(dictionary);
		ArrayList<String>ans = new ArrayList<>();

        solve(s,ans,hs,new ArrayList<>(),0);
		return ans;
	}

	public static void  solve(String s,ArrayList<String> ans , Set<String>hs, ArrayList<String>sub, int start  ){

		if(start == s.length()){
          ans.add(String.join(" ", sub));
		  return ;

		}

		for( int end = start + 1 ;end<=s.length();end++){
			String word = s.substring(start,end);

			if(hs.contains(word)){
				sub.add(word);
                solve(s,ans,hs,sub,end);
				sub.remove(sub.size()-1); // backtracking remove the string 
			}
		}
	}
}
46 views
0 replies
1 upvote

Interview problems

JAVA || Recursion || ArrayList || EASY TO UNDERSTAND

EASY TO UNDERSTAND Using Recursion

and Backtracking 

you just required pen and paper and you are good to go to do this.              

public static ArrayList<String> wordBreak(String s, ArrayList<String> dictionary) {

        // Write your code here.

        ArrayList<String> list= new ArrayList<>();

        solve( s ,dictionary, list, " ");

        return list;

    }

    public static void solve(String s,ArrayList<String> dictionary ,ArrayList<String> list, String ans){

        if(s.length() ==0){

            list.add(ans.trim());

            return;

        }

        for(int i =0;i<s.length();i++){

            String left =s.substring(0,i+1);

            if(dictionary.contains(left)){

            String ros = s.substring(i+1);

            solve(ros,dictionary,list,ans+left+" ");

            

            //ans.delete(del,ans.length());

            }

 

        }

        return;

 

    }

}

Time complextiy : O(n + 2^n)  n→ for string length and 2^n for all possible partition 

space complexity : O(n*2^n) stack space and for extra ArrayList

199 views
0 replies
3 upvotes

Interview problems

java || ArrayList || recursion || backtrack

public static ArrayList<String> wordBreak(String s, ArrayList<String> dictionary) {

        ArrayList<String> ans=new ArrayList<>();

        //if String s is already present in the list  dictionary just add it to ans list;

        if(dictionary.contains(s)) ans.add(s);

        for(int i=1;i<=s.length();i++){

            //takes left part as substring;

            String left=s.substring(0,i);

            //when the left part of a String is found in dicitionary just recursive call for the remaining part and add both to ans List;

            if(dictionary.contains(left)){

                List<String> temp=wordBreak(s.substring(i), dictionary);

                //after recurrsive call add all stored elementfrom temp to ans list;

                for(String sen: temp){

                    ans.add(left+" "+sen);

                }

            }

        }

        return ans;

    }

74 views
0 replies
0 upvotes

Interview problems

JAVA Solution || 100% 🟢 Success

import java.util.* ;
import java.io.*; 
import java.util.ArrayList;

public class Solution {

	public static ArrayList<String> wordBreak(String s, ArrayList<String> dictionary) {
		ArrayList<String> list=new ArrayList();
		solve(s,dictionary,new StringBuilder(),list);
		return list;
	}
	public static void solve(String s, ArrayList<String> dictionary,StringBuilder str,ArrayList<String> list){
		if(s.length()==0){
			list.add(str.toString());
			return;
		}

		StringBuilder word=new StringBuilder();
		for(int i=0;i<s.length();i++){
			word.append(s.charAt(i));

			if(dictionary.contains(word.toString())){
				str.append(word+" ");
				solve(s.substring(i+1),dictionary,str,list);
				int del=str.lastIndexOf(word.toString());
				str.delete(del,str.length());
			}
		}
	}
}
77 views
0 replies
1 upvote

Interview problems

Easy to understand solution

#include <bits/stdc++.h> 
void wordBreak(string &s, vector<string> &dic, vector<string> &ans, string temp,int start){
    if(start == s.size()){
        temp.pop_back();
        ans.push_back(temp);
        return;
    }

    for(int i = start;i<s.size();i++){
        string word = s.substr(start,i-start+1);

        if(find(dic.begin(),dic.end(),word) != dic.end()){
            wordBreak(s,dic,ans,temp+word+" ",i+1);
        }
    }
}

vector<string> wordBreak(string &s, vector<string> &dictionary)
{
    vector<string> ans;
    
    wordBreak(s,dictionary,ans,"",0);

    return ans;

}
644 views
0 replies
0 upvotes

Interview problems

EASY

#include <bits/stdc++.h>

using namespace std;

 

void backtrack(string &s, unordered_set<string> &dictionary, vector<string> &result, string current, int start) {

    if (start == s.length()) {

        result.push_back(current);

        return;

    }

    

    for (int i = start; i < s.length(); i++) {

        string word = s.substr(start, i - start + 1);

        if (dictionary.find(word) != dictionary.end()) {

            string new_current = current.empty() ? word : current + " " + word;

            backtrack(s, dictionary, result, new_current, i + 1);

        }

    }

}

 

vector<string> wordBreak(string &s, vector<string> &dictionary) {

    unordered_set<string> dict(dictionary.begin(), dictionary.end());

    vector<string> result;

    backtrack(s, dict, result, "", 0);

    return result;

}

246 views
0 replies
0 upvotes

Interview problems

Easy Python Trie Solution

from os import *
from sys import *
from collections import *
from math import *

class TrieNode:
    def __init__(self):
        self.children = {}
        self.endOfWord = False

class Trie:

    def __init__(self):
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        curr = self.root

        for c in word:
            if c not in curr.children:
                curr.children[c] = TrieNode()
            curr = curr.children[c]
        
        curr.endOfWord = True
        

    def search(self, word: str) -> bool:
        curr = self.root

        for c in word:
            if c not in curr.children:
                return False
            curr = curr.children[c]
        
        return curr.endOfWord

def wordBreak(s, dictionary):
    trie = Trie()
    for word in dictionary:
        trie.insert(word)

    result = []
    n = len(s)
    def solve(i, curr):
        if i == n:
            result.append(curr.strip())
            return
        
        for j in range(i, n):
            word = s[i: j + 1]
            if trie.search(word):
                solve(j + 1, curr + word + " ")
    
    solve(0,  "")
    return result

38 views
0 replies
0 upvotes

Interview problems

Even Hard Sounds Medium in Python

def wordBreak(s, dictionary):
    def rec(i,w):
        if i==len(s):
            out.append(w)
            return
        for j in range(i,len(s)):
            if s[i:j+1] in dictionary:
                rec(j+1,w+s[i:j+1]+' ')

    out = []

    rec(0,'')
    return out
106 views
0 replies
0 upvotes

Interview problems

7/11 test case passing only. why?

public class Solution {
	static ArrayList<String> ans = new ArrayList<>();
	private static void breakWord(String s, int ind, Set<String> set, StringBuilder sb){
		if(ind >= s.length()) {
			ans.add(sb.toString().trim());
			return;
		}

		String temp;
		int initialLength = sb.length();
		for(int i=ind+1;i<=s.length();i++){
			temp = s.substring(ind, i);
			if(set.contains(temp)){
				sb.append(temp).append(" ");
				breakWord(s, i, set, sb);
				sb.delete(initialLength, sb.length());
			}
		}
	}

	public static ArrayList<String> wordBreak(String s, ArrayList<String> dictionary) {
		// Write your code here.
		Set<String> set = new HashSet<>(dictionary);
		StringBuilder sb = new StringBuilder();
		breakWord(s, 0, set, sb);
		return ans;
	}
}
104 views
1 reply
0 upvotes
Full screen
Console