# 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.

Examples:

`Given a dictionary ["Cat", "Mat", "Ca",      "tM", "at", "C", "Dog", "og", "Do"]Input :  Pattern "CatMat"Output : 1 Explanation: we can break the sentencesin three ways, as follows:CatMat = [ Cat Mat ]  break 1CatMat = [ Ca tM at ] break 2CatMat = [ C at Mat ] break 2  so the          output is: 1Input : DogcatOutput : 1`

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 keylength   ....If we found a leaf node in trie         MinBreak( Trie, key, level+1, i )`

Below is the implementation of above idea

## C++

## Java

## Python3

## C#

 `
``// C# program to find minimum breaks needed
// to break a string in dictionary words.
using System;

class Trie
{

TrieNode root = new TrieNode();
int minWordBreak = int.MaxValue ;

// Trie node
public class TrieNode
{
public bool endOfTree;
public TrieNode []children = new TrieNode[26];
public TrieNode()
{
endOfTree = false;
for(int i = 0; i < 26; i++)
{
children[i] = null;
}
}
}

// If not present, inserts a key
// into the trie If the key is the
// prefix of trie node, just marks leaf node
void insert(String key)
{
int length = key.Length;

int index;

TrieNode pcrawl = root;

for(int i = 0; i < length; i++)
{
index = key[i]- 'a';

if(pcrawl.children[index] == null)
pcrawl.children[index] = new TrieNode();

pcrawl = pcrawl.children[index];
}

// mark last node as leaf
pcrawl.endOfTree = true;

}

// function break the string into minimum cut
// such the every substring after breaking
// in the dictionary.
void minWordBreaks(String key)
{
minWordBreak = int.MaxValue;
minWordBreakUtil(root, key, 0, int.MaxValue, 0);
}

void minWordBreakUtil(TrieNode node, String key,
int start, int min_Break, int level)
{
TrieNode pCrawl = node;

// base case, update minimum Break
if (start == key.Length)
{
min_Break = Math.Min(min_Break, level - 1);
if(min_Break < minWordBreak)
{
minWordBreak = min_Break;
}
return;
}

// traverse given key(pattern)
for (int i = start; i < key.Length; i++)
{
int index = key[i] - 'a';
if (pCrawl.children[index]==null)
return;

// if we find a condition were we can
// move to the next word in a trie
// dictionary
if (pCrawl.children[index].endOfTree)
{
minWordBreakUtil(root, key, i + 1,
min_Break, level + 1);
}
pCrawl = pCrawl.children[index];
}
}

// Driver code
public static void Main(String[] args)
{
String []keys = {"cat", "mat", "ca", "ma",
"at", "c", "dog", "og", "do" };

Trie trie = new Trie();

// Construct trie
int i;
for (i = 0; i < keys.Length ; i++)
trie.insert(keys[i]);

trie.minWordBreaks("catmatat");
Console.WriteLine(trie.minWordBreak);
}
}

// This code is contributed by 29AjayKumar
`

## Javascript

 ``

Output
```2

```

Time Complexity: O(n*n*L) where n is the length of the input string and L is the maximum length of word in the dictionary.
Auxiliary Space: O(ALPHABET_SIZE^L+n*L)

### Approach 2: Using Dynamic Programming

• We maintain an array dp where dp[i] represents the minimum number of breaks needed to break the substring s[0…i-1] into dictionary words.
• We initialize dp[0] = 0 since the empty string can be broken into zero words.
• For each position i in the string, we iterate over all dictionary words and check if the substring ending at position i matches the current dictionary word.
• If it does, we update dp[i] to be the minimum of dp[i] and dp[i – len] + 1, where len is the length of the current dictionary word.
• Finally, we return dp[n] – 1, where n is the length of the input string, since the number of breaks needed is one less than the number of words.

## C++

 `<``div` `id=``"highlighter_960148"` `class``=``"syntaxhighlighter nogutter  "``>
<``div` `class``=``"container"``><``div` `class``=``"line number1 index0 alt2"``>#include <``div` `class``=``"line number2 index1 alt1"``>``using`` ``namespace`` std;<``div` `class``=``"line number3 index2 alt2"``> <``div` `class``=``"line number4 index3 alt1"``>``const`` ``int`` INF = 1e9;<``div` `class``=``"line number5 index4 alt2"``> <``div` `class``=``"line number6 index5 alt1"``>``int`` minWordBreak(string s, vector& dict) {<``div` `class``=``"line number7 index6 alt2"``>    ``int`` n = s.length();<``div` `class``=``"line number8 index7 alt1"``>    vector<``int``> dp(n + 1, INF);<``div` `class``=``"line number9 index8 alt2"``>    dp[0] = 0;<``div` `class``=``"line number10 index9 alt1"``> <``div` `class``=``"line number11 index10 alt2"``>    ``for`` (``int`` i = 1; i <= n; i++) {<``div` `class``=``"line number12 index11 alt1"``>        ``for`` (string word : dict) {<``div` `class``=``"line number13 index12 alt2"``>            ``int`` len = word.length();<``div` `class``=``"line number14 index13 alt1"``>            ``if`` (i >= len && s.substr(i - len, len) == word) {<``div` `class``=``"line number15 index14 alt2"``>                dp[i] = min(dp[i], dp[i - len] + 1);<``div` `class``=``"line number16 index15 alt1"``>            }<``div` `class``=``"line number17 index16 alt2"``>        }<``div` `class``=``"line number18 index17 alt1"``>    }<``div` `class``=``"line number19 index18 alt2"``> <``div` `class``=``"line number20 index19 alt1"``>    ``return`` dp[n] - 1;<``div` `class``=``"line number21 index20 alt2"``>}<``div` `class``=``"line number22 index21 alt1"``> <``div` `class``=``"line number23 index22 alt2"``>``int`` main() {<``div` `class``=``"line number24 index23 alt1"``>    vector dict = {``"Cat"``, ``"Mat"``, ``"Ca"``, ``"Ma"``, ``"at"``, ``"C"``, ``"Dog"``, ``"og"``, ``"Do"``};<``div` `class``=``"line number25 index24 alt2"``>    string s = ``"CatMatat"``;<``div` `class``=``"line number26 index25 alt1"``>    cout << minWordBreak(s, dict) << endl;<``div` `class``=``"line number27 index26 alt2"``>    ``return`` 0;<``div` `class``=``"line number28 index27 alt1"``>}
`

## Java

## Python3

## C#

## Javascript

Output
```2

```

Note that this code has a time complexity of O(n*m), where n is the length of the input string and m is the size of the dictionary. This is because we iterate over all positions in the string and for each position, we iterate over all words in the dictionary.

Previous
Next