Minimum Word Break
Given a string s, break s such that every substring of the partition can be found in the dictionary. Return the minimum break needed.
Given a dictionary ["Cat", "Mat", "Ca", "tM", "at", "C", "Dog", "og", "Do"] Input : Pattern "CatMat" Output : 1 Explanation: we can break the sentences in three ways, as follows: CatMat = [ Cat Mat ] break 1 CatMat = [ Ca tM at ] break 2 CatMat = [ C at Mat ] break 2 so the output is: 1 Input : Dogcat Output : 1
Asked in: Facebook
Solution of this problem is based on the WordBreak Trie solution and level ordered graph. We start traversing given pattern and start finding a character of pattern in a trie. If we reach a node(leaf) of a trie from where we can traverse a new word of a trie(dictionary), we increment level by one and call search function for rest of the pattern character in a trie. In the end, we return minimum Break.
MinBreak(Trie, key, level, start = 0 ) .... If start == key.length() ...update min_break for i = start to keylenght ....If we found a leaf node in trie MinBreak( Trie, key, level+1, i )
Below is the implementation of above idea
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.