(Method signature is given with parameters)
Try to visualize me writing this code at an interview, and please be brutal while judging it.
Problem:
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
For example, given
s = "catsanddog", dict = ["cat", "cats", "and", "sand", "dog"]
A solution is
["cats and dog", "cat sand dog"]
Time complexity: I don't know how to analyze it, \$O(n)\$, since I visit each char of the string for sure, but since I am backtracking, I visit it again constant time. I don't know, so please explain
Space Complexity: \$O(n)\$
public ArrayList<String> wordBreak(String s, Set<String> dict) {
ArrayList<String> sentences = new ArrayList<String>();
wordBreakHelper(s, dict, 0, new StringBuilder(), sentences);
return sentences;
}
private static void wordBreakHelper(String givenSentence, Set<String> dictionary, int index, StringBuilder path, ArrayList<String> results){
if(givenSentence.length() == 0){
results.add(path.toString());
}
if(index > givenSentence.length()){
return;
}
for(int i = index; i < givenSentence.length(); i++){
boolean isSpace = false;
if(dictionary.contains(givenSentence.substring(0, i+1))){
if(i+1 == givenSentence.length()){
path.append(givenSentence.substring(0, i+1));
}else{
path.append(givenSentence.substring(0, i+1) +" ");
isSpace = true;
}
wordBreakHelper(givenSentence.substring(i+1), dictionary, 0, path, results);
if(isSpace == true){
path.replace(path.length() - givenSentence.substring(0, i+2).length() , path.length(), "");
}else{
path.replace(path.length() - givenSentence.substring(0, i+1).length() , path.length(), "");
}
}
}
}