The Wayback Machine - https://web.archive.org/web/20241119092205/https://www.geeksforgeeks.org/word-break-problem-dp-32/
Open In App

Word Break

Last Updated : 15 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details. 
This is a famous Google interview question, also being asked by many other companies now a days.

Consider the following dictionary
{ i, like, sam, sung, samsung, mobile, ice,
cream, icecream, man, go, mango}

Input: ilike
Output: Yes
The string can be segmented as “i like”.

Input: ilikesamsung
Output: Yes
The string can be segmented as “i like samsung”
or “i like sam sung”.

Recursive implementation: 
The idea is simple, we consider each prefix and search for it in dictionary. If the prefix is present in dictionary, we recur for rest of the string (or suffix). If the recursive call for suffix returns true, we return true, otherwise we try next prefix. If we have tried all prefixes and none of them resulted in a solution, we return false.

C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

// Function to check if the given string can be broken
// down into words from the word list
bool WordBreak(const string& str, const vector<string>& d)
{
    // If the string is empty, it can be broken down into
    // an empty list of words
    if (str.empty())
        return true;

    int n = str.length();

    // Try every prefix of length i 
    for (int i = 1; i <= n; ++i) {
        
        // if the prefix of length i is a dictionary word
        // and rest of the string can also be broken into
        // valid words, return true
        string prefix = str.substr(0, i);
        if (find(d.begin(), d.end(), prefix) != d.end() && 
            WordBreak(str.substr(i), d)) {
            return true;
        }
    }

    return false;
}

int main()
{
    vector<string> d = { "mobile", "samsung",  "sam",  "sung", "man",
                         "mango",  "icecream", "and",  "go",   "i",
                         "like",   "ice",      "cream" };
    
    cout << (WordBreak("ilikesamsung", d) ? "Yes\n" : "No\n");
    cout << (WordBreak("iiiiiiii", d) ? "Yes\n" : "No\n");
    cout << (WordBreak("", d) ? "Yes\n" : "No\n");
    cout << (WordBreak("ilikelikeimangoiii", d) ? "Yes\n" : "No\n");
    cout << (WordBreak("samsungandmango", d) ? "Yes\n" : "No\n");
    cout << (WordBreak("samsungandmangok", d) ? "Yes\n" : "No\n");

    return 0;
}
Java
import java.util.*;

public class Main {
    // Function to check if the given word can be broken
    // down into words from the wordList
    static boolean wordBreak(List<String> wordList,
                             String word)
    {
        // If the word is empty, it can be broken down into
        // an empty list of words
        if (word.isEmpty()) {
            return true;
        }

        int wordLen = word.length();

        // Check if the word can be broken down into
        // words from the wordList
        for (int i = 1; i <= wordLen; ++i) {
            String prefix = word.substring(0, i);

            if (wordList.contains(prefix)
                && wordBreak(wordList, word.substring(i))) {
                return true;
            }
        }

        return false;
    }

    public static void main(String[] args)
    {
        List<String> wordList = Arrays.asList(
            "mobile", "samsung", "sam", "sung", "man",
            "mango", "icecream", "and", "go", "i", "like",
            "ice", "cream");

        boolean result
            = wordBreak(wordList, "ilikesamsung");

        System.out.println(result); // Output: true
    }
}
Python
# Function to check if the given word can be broken
# down into words from the wordList
def wordBreak(wordList, word):
    # If the word is empty, it can be broken down into
    # an empty list of words
    if not word:
        return True
    
    wordLen = len(word)
    
    # Check if the word can be broken down into
    # words from the wordList
    for i in range(1, wordLen + 1):
        prefix = word[:i]
        
        if prefix in wordList and wordBreak(wordList, word[i:]):
            return True
    
    return False

wordList = ["mobile", "samsung", "sam", "sung", "man",
                "mango", "icecream", "and", "go", "i",
                "like", "ice", "cream"]
    
result = wordBreak(wordList, "ilikesamsung")
    
print(result)
C#
using System;
using System.Collections.Generic;
using System.Linq;

class GFG {
    // Function to check if the given word can be broken
    // down into words from the wordList
    public static bool WordBreak(List<string> wordList,
                                 string word)
    {
        // If the word is empty, it can be broken down into
        // an empty list of words
        if (word == "")
            return true;

        int wordLen = word.Length;

        // Check if the word can be broken down into
        // words from the wordList
        return Enumerable.Range(1, wordLen)
            .Any(i
                 => wordList.Contains(word.Substring(0, i))
                   && WordBreak(wordList,
                                word.Substring(i)));
    }
    
    public static void Main(string[] args)
    {

        Console.WriteLine(WordBreak(
            new List<string>(new string[] {
                "mobile", "samsung", "sam", "sung", "man",
                "mango", "icecream", "and", "go", "i",
                "like", "ice", "cream" }),
            "ilikesamsung"));
    }
}
JavaScript
// Function to check if the given word can be broken down into words from the wordList
function wordBreak(wordList, word) {
    // If the word is empty, it can be broken down into an empty list of words
    if (word === '') {
        return true;
    }

    const wordLen = word.length;

    // Check if the word can be broken down into words from the wordList
    for (let i = 1; i <= wordLen; i++) {
        const prefix = word.substr(0, i);

        if (wordList.includes(prefix) && wordBreak(wordList, word.substr(i))) {
            return true;
        }
    }

    return false;
}

// Main function
function main() {
    const wordList = [
        "mobile", "samsung", "sam", "sung", "man",
        "mango", "icecream", "and", "go", "i",
        "like", "ice", "cream"
    ];

    const result = wordBreak(wordList, "ilikesamsung");

    console.log(result); // Output: true
}

// Call the main function
main();

Output
Yes
Yes
Yes
Yes
Yes
No


Dynamic Programming 
Why Dynamic Programming? The above problem exhibits overlapping sub-problems. For example, see the following partial recursion tree for string “abcde” in the worst case.
 

wordBreak

CPP
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

// Returns true if dictionary d contains the given word
bool isInDict(const string &word, unordered_set<string>& d) {
    return d.find(word) != d.end();
}

// Returns true of a given string can be broken into
// dictionary d words, else false
bool wordBreak(const string &str, unordered_set<string>& d) {
    
    int n = str.size();
    
    // dp[i] is gping to be true if the prefix of 
    // length i can be broken into words.
    vector<bool> dp(n + 1, false);
    dp[0] = true; // Answe is true for an empty string
 
    for (int i = 1; i <= n; i++) {
        
        // Check for smaller strings and if we find
        // a j such that a prefix of length j can be
        // broken and str[j..i-1] is also a valid word
        for (int j = 0; j < i; j++) {
            if (dp[j] && isInDict(str.substr(j, i - j), d)) {
                dp[i] = true;
                break;
            }
        }
    }
    return dp[n];
}

int main() {
    vector<string> words = {"mobile", "samsung", "sam", 
          "sung", "man", "mango", "icecream", "and", "go", 
          "i", "like", "ice", "cream"};

    unordered_set<string> d(words.begin(), words.end());

    cout << (wordBreak("ilikesamsung", d) ? "Yes\n" : "No\n");
    cout << (wordBreak("iiiiiiii", d) ? "Yes\n" : "No\n");
    cout << (wordBreak("", d) ? "Yes\n" : "No\n");
    cout << (wordBreak("ilikelikeimangoiii", d) ? "Yes\n" : "No\n");
    cout << (wordBreak("samsungandmango", d) ? "Yes\n" : "No\n");
    cout << (wordBreak("samsungandmangok", d) ? "Yes\n" : "No\n");

    return 0;
}
Java
// A Dynamic Programming based program to test whether a given String can
// be segmented into space separated words in dictionary
import java.util.*;

class GFG{

/* A utility function to check whether a word is present in dictionary or not.
  An array of Strings is used for dictionary.  Using array of Strings for
  dictionary is definitely not a good idea. We have used for simplicity of
  the program*/
static boolean dictionaryContains(String word)
{
    String dictionary[] = {"mobile","samsung","sam","sung","man","mango",
                           "icecream","and","go","i","like","ice","cream"};
    int size = dictionary.length;
    for (int i = 0; i < size; i++)
        if (dictionary[i].compareTo(word) == 0)
           return true;
    return false;
}

// Returns true if String can be segmented into space separated
// words, otherwise returns false
static boolean wordBreak(String str)
{
    int size = str.length();
    if (size == 0)   return true;

    // Create the DP table to store results of subproblems. The value wb[i]
    // will be true if str[0..i-1] can be segmented into dictionary words,
    // otherwise false.
    boolean []wb = new boolean[size+1];
   
    for (int i=1; i<=size; i++)
    {
        // if wb[i] is false, then check if current prefix can make it true.
        // Current prefix is "str.substring(0, i)"
        if (wb[i] == false && dictionaryContains( str.substring(0, i) ))
            wb[i] = true;

        // wb[i] is true, then check for all subStrings starting from
        // (i+1)th character and store their results.
        if (wb[i] == true)
        {
            // If we reached the last prefix
            if (i == size)
                return true;

            for (int j = i+1; j <= size; j++)
            {
                // Update wb[j] if it is false and can be updated
                // Note the parameter passed to dictionaryContains() is
                // subString starting from index 'i' and length 'j-i'
                if (wb[j] == false && dictionaryContains( str.substring(i, j) ))
                    wb[j] = true;

                // If we reached the last character
                if (j == size && wb[j] == true)
                    return true;
            }
        }
    }

    /* Uncomment these lines to print DP table "wb[]"
     for (int i = 1; i <= size; i++)
        System.out.print(" " +  wb[i]; */

    // If we have tried all prefixes and none of them worked
    return false;
}

// Driver program to test above functions
public static void main(String[] args)
{
    if(wordBreak("ilikesamsung"))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
    if(wordBreak("iiiiiiii"))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
    if(wordBreak(""))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
    if(wordBreak("ilikelikeimangoiii"))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
    if(wordBreak("samsungandmango"))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
    if(wordBreak("samsungandmangok"))
        System.out.print("Yes\n");
    else
        System.out.print("No\n");
   }
}

// This code is contributed by Rajput-Ji
Python
# A Dynamic Programming based program to test whether a given String can
# be segmented into space separated words in dictionary

# A utility function to check whether a word is present in dictionary or not.
# An array of Strings is used for dictionary. Using array of Strings for
# dictionary is definitely not a good idea. We have used for simplicity of the
# program
def dictionaryContains(word):
    dictionary = [ "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i",
                "like", "ice", "cream" ]
    size = len(dictionary)
    for i in range(size):
        if (dictionary[i]== word):
            return True
    return False

# Returns True if String can be segmented into space separated
# words, otherwise returns False
def wordBreak(Str):
    size = len(Str)
    if (size == 0):
        return True

        # Create the DP table to store results of subproblems. The value wb[i]
        # will be True if str[0..i-1] can be segmented into dictionary words,
        # otherwise False.
    wb = [False for i in range(size + 1)]

    for i in range(1,size + 1):
        # if wb[i] is False, then check if current prefix can make it True.
        # Current prefix is "str.substring(0, i)"
        if (wb[i] == False and dictionaryContains(Str[0: i])):
            wb[i] = True

        # wb[i] is True, then check for all subStrings starting from
        # (i+1)th character and store their results.
        if (wb[i] == True):
            # If we reached the last prefix
            if (i == size):
                return True

            for j in range(i + 1,size + 1):
                # Update wb[j] if it is False and can be updated
                # Note the parameter passed to dictionaryContains() is
                # subString starting from index 'i' and length 'j-i'
                if (wb[j] == False and dictionaryContains(Str[i: j])):
                    wb[j] = True

                # If we reached the last character
                if (j == size and wb[j] == True):
                    return True
                
            

    # If we have tried all prefixes and none of them worked
    return False

# Driver program to test above functions
    
if (wordBreak("ilikesamsung")):
    print("Yes")
else:
    print("No")
if (wordBreak("iiiiiiii")):
    print("Yes")
else:
    print("No")
if (wordBreak("")):
    print("Yes")
else:
    print("No")
if (wordBreak("ilikelikeimangoiii")):
    print("Yes")
else:
    print("No")
if (wordBreak("samsungandmango")):
    print("Yes")
else:
    print("No")
if (wordBreak("samsungandmangok")):
    print("Yes")
else:
    print("No")

# This code is contributed by shinjanpatra
C#
// A Dynamic Programming based program to test whether a given String can
// be segmented into space separated words in dictionary

// Include namespace system
using System;

public class GFG
{
    // A utility function to check whether a word is present in dictionary or not.
    //  An array of Strings is used for dictionary.  Using array of Strings for
    //  dictionary is definitely not a good idea. We have used for simplicity of
    //  the program
    public static bool dictionaryContains(String word)
    {
        String[] dictionary = {"mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream"};
        var size = dictionary.Length;
        for (int i = 0; i < size; i++)
        {
            if (string.CompareOrdinal(dictionary[i],word) == 0)
            {
                return true;
            }
        }
        return false;
    }
    // Returns true if String can be segmented into space separated
    // words, otherwise returns false
    public static bool wordBreak(String str)
    {
        var size = str.Length;
        if (size == 0)
        {
            return true;
        }
        // Create the DP table to store results of subproblems. The value wb[i]
        // will be true if str[0..i-1] can be segmented into dictionary words,
        // otherwise false.
        bool[] wb = new bool[size + 1];
        for (int i = 1; i <= size; i++)
        {
            // if wb[i] is false, then check if current prefix can make it true.
            // Current prefix is "str.substring(0, i)"
            if (wb[i] == false && GFG.dictionaryContains(str.Substring(0,i-0)))
            {
                wb[i] = true;
            }
            // wb[i] is true, then check for all subStrings starting from
            // (i+1)th character and store their results.
            if (wb[i] == true)
            {
                // If we reached the last prefix
                if (i == size)
                {
                    return true;
                }
                for (int j = i + 1; j <= size; j++)
                {
                    // Update wb[j] if it is false and can be updated
                    // Note the parameter passed to dictionaryContains() is
                    // subString starting from index 'i' and length 'j-i'
                    if (wb[j] == false && GFG.dictionaryContains(str.Substring(i,j-i)))
                    {
                        wb[j] = true;
                    }
                    // If we reached the last character
                    if (j == size && wb[j] == true)
                    {
                        return true;
                    }
                }
            }
        }
        // Uncomment these lines to print DP table "wb[]"
        //     for (int i = 1; i <= size; i++)
        //        System.out.print(" " +  wb[i];
        // If we have tried all prefixes and none of them worked
        return false;
    }
    // Driver program to test above functions
    public static void Main(String[] args)
    {
        if (GFG.wordBreak("ilikesamsung"))
        {
            Console.Write("Yes\n");
        }
        else 
        {
            Console.Write("No\n");
        }
        if (GFG.wordBreak("iiiiiiii"))
        {
            Console.Write("Yes\n");
        }
        else 
        {
            Console.Write("No\n");
        }
        if (GFG.wordBreak(""))
        {
            Console.Write("Yes\n");
        }
        else 
        {
            Console.Write("No\n");
        }
        if (GFG.wordBreak("ilikelikeimangoiii"))
        {
            Console.Write("Yes\n");
        }
        else 
        {
            Console.Write("No\n");
        }
        if (GFG.wordBreak("samsungandmango"))
        {
            Console.Write("Yes\n");
        }
        else 
        {
            Console.Write("No\n");
        }
        if (GFG.wordBreak("samsungandmangok"))
        {
            Console.Write("Yes\n");
        }
        else 
        {
            Console.Write("No\n");
        }
    }
}

// This code is contributed by mukulsomukesh
JavaScript
// A Dynamic Programming based program to test whether a given String can
// be segmented into space separated words in dictionary

    /*
     * A utility function to check whether a word is present in dictionary or not.
     * An array of Strings is used for dictionary. Using array of Strings for
     * dictionary is definitely not a good idea. We have used for simplicity of the
     * program
     */
    function dictionaryContains( word) {
        var dictionary = [ "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i",
                "like", "ice", "cream" ];
        var size = dictionary.length;
        for (var i = 0; i < size; i++)
            if (dictionary[i]===(word))
                return true;
        return false;
    }

    // Returns true if String can be segmented into space separated
    // words, otherwise returns false
    function wordBreak( str) {
        var size = str.length;
        if (size == 0)
            return true;

        // Create the DP table to store results of subproblems. The value wb[i]
        // will be true if str[0..i-1] can be segmented into dictionary words,
        // otherwise false.
        var wb = Array(size + 1).fill(false);

        for (var i = 1; i <= size; i++) {
            // if wb[i] is false, then check if current prefix can make it true.
            // Current prefix is "str.substring(0, i)"
            if (wb[i] == false && dictionaryContains(str.substring(0, i)))
                wb[i] = true;

            // wb[i] is true, then check for all subStrings starting from
            // (i+1)th character and store their results.
            if (wb[i] == true) {
                // If we reached the last prefix
                if (i == size)
                    return true;

                for (j = i + 1; j <= size; j++) {
                    // Update wb[j] if it is false and can be updated
                    // Note the parameter passed to dictionaryContains() is
                    // subString starting from index 'i' and length 'j-i'
                    if (wb[j] == false && dictionaryContains(str.substring(i, j)))
                        wb[j] = true;

                    // If we reached the last character
                    if (j == size && wb[j] == true)
                        return true;
                }
            }
        }

        /*
         * Uncomment these lines to print DP table "wb" for (i = 1; i <= size;
         * i++) document.write(" " + wb[i];
         */

        // If we have tried all prefixes and none of them worked
        return false;
    }

    // Driver program to test above functions
    
        if (wordBreak("ilikesamsung"))
            console.log("Yes<br/>");
        else
            console.log("No<br/>");
        if (wordBreak("iiiiiiii"))
            console.log("Yes<br/>");
        else
            console.log("No<br/>");
        if (wordBreak(""))
            console.log("Yes<br/>");
        else
            console.log("No<br/>");
        if (wordBreak("ilikelikeimangoiii"))
            console.log("Yes<br/>");
        else
            document.write("No<br/>");
        if (wordBreak("samsungandmango"))
            console.log("Yes<br/>");
        else
            console.log("No<br/>");
        if (wordBreak("samsungandmangok"))
            console.log("Yes<br/>");
        else
            console.log("No<br/>");

// This code contributed by Rajput-Ji 

Output
Yes
Yes
Yes
Yes
Yes
No

Time complexity : O(n^3 + dict_len), where n is the length of the input string. We create a dictionary in a hash set.
Auxiliary Space : O(n + dict_len).

Optimized Dynamic Programming: 
In this approach, apart from the dp table, we also maintain all the prefix lengths which have already matched. We store this in an array matched_len[]. For the current prefix length to be checked, we consider only those prefixes which have already matched using matched_len[]. This way we avoid unnecessary iterations and string comparisons.

C++
#include <bits/stdc++.h>
using namespace std;

// Returns true if dictionary d contains the given word
bool isInDict(const string &word, unordered_set<string> &d){
    return d.find(word) != d.end();
}

bool wordBreak(const string &s, unordered_set<string> &d)
{
    int n = s.size();
    if (n == 0)
        return true;

    vector<bool> dp(n + 1, 0);
    dp[0] = true;

    // matched_len stores lengths of
    // prefixes for which we have got
    // the result as true. 
    vector<int> matched_len;
    matched_len.push_back(0);

    for (int i = 1; i <= n; i++)
    {
        int msize = matched_len.size();

        // Consider all already matched lengths
        // and check only for remaining strings
        // after these already matched
        for (int j = msize - 1; j >= 0; j--)
        {
            int len = matched_len[j];
           
            // rem is substring starting from
            // matched_len[j] and of length 
            // i - matched_len[j]
            string rem = s.substr(len, i - len);

            // If the remaining substring is 
            // also a word
            if (isInDict(rem, d))
            {
                dp[i] = 1;
                matched_len.push_back(i);
                break;
            }
        }
    }
    return dp[n];
}

int main()
{
    vector<string> words = {"mobile", "samsung", "sam", "sung", "man", "mango", "icecream",
                            "and",    "go",      "i",   "like", "ice", "cream"};

    unordered_set<string> d(words.begin(), words.end());

    cout << (wordBreak("ilikesamsung", d) ? "Yes\n" : "No\n");
    cout << (wordBreak("iiiiiiii", d) ? "Yes\n" : "No\n");
    cout << (wordBreak("", d) ? "Yes\n" : "No\n");
    cout << (wordBreak("ilikelikeimangoiii", d) ? "Yes\n" : "No\n");
    cout << (wordBreak("samsungandmango", d) ? "Yes\n" : "No\n");
    cout << (wordBreak("samsungandmangok", d) ? "Yes\n" : "No\n");

    return 0;
}
Java
import java.io.*;
import java.util.*;

class GFG {
  
  public static boolean wordBreak(String s, List<String> dictionary) {
        // create a dp table to store results of subproblems
        // value of dp[i] will be true if string s can be segmented
        // into dictionary words from 0 to i.
        boolean[] dp = new boolean[s.length() + 1];
    
        // dp[0] is true because an empty string can always be segmented. 
        dp[0] = true;
    
        for(int i = 0; i <= s.length(); i++){
            for(int j = 0; j < i; j++){
                if(dp[j] && dictionary.contains(s.substring(j, i))){
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
  
    public static void main (String[] args) {
      String[] dictionary = { "mobile", "samsung",  "sam",  "sung", "man",
                "mango",  "icecream", "and",  "go",   "i",
                "like",   "ice",      "cream" };

        List<String> dict = new ArrayList<>();
        for(String s : dictionary){
            dict.add(s);
        }

        if (wordBreak("ilikesamsung", dict)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
        if (wordBreak("iiiiiiii", dict)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
        if (wordBreak("", dict)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
        if (wordBreak("samsungandmango", dict)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
        if (wordBreak("ilikesamsung", dict)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
        if (wordBreak("samsungandmangok", dict)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
      
    }
}
Python
def wordBreak(s, dictionary): 
    
    # create a dp table to store results of subproblems
    # value of dp[i] will be true if string s can be segmented
    # into dictionary words from 0 to i.
    dp = [False for i in range(len(s) + 1)]

    # dp[0] is true because an empty string can always be segmented.
    dp[0] = True

    for i in range(len(s) + 1):
        for j in range(i):
            if dp[j] and s[j: i] in dictionary:
                dp[i] = True
                break
    
    return dp[len(s)]
 
# driver code
dictionary = [ "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i", "like", "ice", "cream" ]

dict = set()
for s in dictionary:
    dict.add(s)

if (wordBreak("ilikesamsung", dict)):
    print("Yes")
else :
    print("No")

if (wordBreak("iiiiiiii", dict)):
    print("Yes")
else:
    print("No")

if (wordBreak("", dict)):
    print("Yes")
else:
    print("No")

if (wordBreak("samsungandmango", dict)):
    print("Yes")
else:
    print("No")

if (wordBreak("ilikesamsung", dict)):
    print("Yes")
else:
    print("No")

if (wordBreak("samsungandmangok", dict)):
    print("Yes")
else:
    print("No")

# This code is contributed by shinjanpatra
C#
using System;
using System.Collections.Generic;

public class WordBreakProgram {
    // A utility function to check whether a word
    // is present in dictionary or not. A HashSet of
    // strings is used for dictionary.
    static bool
    DictionaryContains(HashSet<string> dictionary,
                       string word)
    {
        return dictionary.Contains(word);
    }

    // Returns true if string can be segmented into space
    // separated words, otherwise returns false
    static bool WordBreak(string s,
                          HashSet<string> dictionary)
    {
        int n = s.Length;
        if (n == 0)
            return true;

        // Create the DP table to store results of
        // subproblems. The value dp[i] will be true if
        // str[0..i] can be segmented into dictionary words,
        // otherwise false.
        bool[] dp = new bool[n + 1];

        // matchedIndex array represents the indexes for
        // which dp[i] is true. Initially only -1 element is
        // present in this array.
        List<int> matchedIndex = new List<int>();
        matchedIndex.Add(-1);

        for (int i = 0; i < n; i++) {
            int msize = matchedIndex.Count;

            // Flag value which tells that a substring
            // matches with given words or not.
            int f = 0;

            // Check all the substring from the indexes
            // matched earlier. If any of that substring
            // matches than make flag value = 1;
            for (int j = msize - 1; j >= 0; j--) {
                // sb is substring starting from
                // matchedIndex[j]
                // + 1  and of length i - matchedIndex[j]
                string sb
                    = s.Substring(matchedIndex[j] + 1,
                                  i - matchedIndex[j]);

                if (DictionaryContains(dictionary, sb)) {
                    f = 1;
                    break;
                }
            }

            // If substring matches than do dp[i] = 1 and
            // push that index in matchedIndex array.
            if (f == 1) {
                dp[i] = true;
                matchedIndex.Add(i);
            }
        }
        return dp[n - 1];
    }

    // Driver code
    public static void Main()
    {
        HashSet<string> dictionary = new HashSet<string>{
            "mobile", "samsung",  "sam",  "sung", "man",
            "mango",  "icecream", "and",  "go",   "i",
            "like",   "ice",      "cream"
        };

        Console.WriteLine(
            WordBreak("ilikesamsung", dictionary) ? "Yes"
                                                  : "No");
        Console.WriteLine(WordBreak("iiiiiiii", dictionary)
                              ? "Yes"
                              : "No");
        Console.WriteLine(WordBreak("", dictionary) ? "Yes"
                                                    : "No");
        Console.WriteLine(
            WordBreak("ilikelikeimangoiii", dictionary)
                ? "Yes"
                : "No");
        Console.WriteLine(
            WordBreak("samsungandmango", dictionary)
                ? "Yes"
                : "No");
        Console.WriteLine(
            WordBreak("samsungandmangok", dictionary)
                ? "Yes"
                : "No");
    }
}
// This code is contributed by Rohit Yadav
JavaScript
    function wordBreak( s, dictionary) 
    {
    
        // create a dp table to store results of subproblems
        // value of dp[i] will be true if string s can be segmented
        // into dictionary words from 0 to i.
        var dp = Array(s.length + 1).fill(false);

        // dp[0] is true because an empty string can always be segmented.
        dp[0] = true;

        for (var i = 0; i <= s.length; i++) {
            for (var j = 0; j < i; j++) {
                if (dp[j] && dictionary.has(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length];
    }

    
        var dictionary = [ "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i",
                "like", "ice", "cream" ];

        var dict = new Set();
        for (var s of dictionary) {
            dict.add(s);
        }

        if (wordBreak("ilikesamsung", dict)) {
            console.log("<br/>Yes");
        } else {
            console.log("<br/>No");
        }
        if (wordBreak("iiiiiiii", dict)) {
            console.log("<br/>Yes");
        } else {
            console.log("<br/>No");
        }
        if (wordBreak("", dict)) {
            console.log("<br/>Yes");
        } else {
            console.log("<br/>No");
        }
        if (wordBreak("samsungandmango", dict)) {
            console.log("<br/>Yes");
        } else {
            console.log("<br/>No");
        }
        if (wordBreak("ilikesamsung", dict)) {
            console.log("<br/>Yes");
        } else {
            console.log("<br/>No");
        }
        if (wordBreak("samsungandmangok", dict)) {
            console.log("<br/>Yes");
        } else {
            console.log("<br/>No");
        }

// This code is contributed by Rajput-Ji

Output
Yes
Yes
Yes
Yes
Yes
No

Word Break Problem | (Trie solution)
Word Break Problem using Backtracking

 



Previous Article
Next Article

Similar Reads

Word Break Problem | DP-32 | Set - 2
Given a non-empty sequence S and a dictionary dict[] containing a list of non-empty words, print all possible ways to break the sentence in individual dictionary words.Examples: Input: S = "catsanddog" dict[] = {"cat", "cats", "and", "sand", "dog"} Output: "cats and dog" "cat sand dog"Input: S = "pineapplepenapple" dict[] = {"apple", "pen", "applep
15 min read
Word Break Problem using Backtracking
Given a valid sentence without any spaces between the words and a dictionary of valid English words, find all possible ways to break the sentence into individual dictionary words. Example: Consider the following dictionary { i, like, sam, sung, samsung, mobile, ice, and, cream, icecream, man, go, mango} Input: "ilikesamsungmobile" Output: i like sa
8 min read
Word Break Problem | (Trie solution)
Given an input string and a dictionary of words, find out if the input string can be segmented into a space-separated sequence of dictionary words. See following examples for more details. This is a famous Google interview question, also being asked by many other companies now a days. Consider the following dictionary { i, like, sam, sung, samsung,
13 min read
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 1Cat
13 min read
Find the word from a given sentence having given word as prefix
Given a string S representing a sentence and another string word, the task is to find the word from S which has the string word as a prefix. If no such word is present in the string, print -1. Examples: Input: S = "Welcome to Geeksforgeeks", word="Gee"Output: GeeksforgeeksExplanation:The word "Geeksforgeeks" in the sentence has the prefix "Gee". In
8 min read
Word Ladder (Length of shortest chain to reach a target word)
Given a dictionary, and two words 'start' and 'target' (both of same length). Find length of the smallest chain from 'start' to 'target' if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may be assumed that the 'target' word exists in dic
15+ min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest common prefix in both of them? It is “geeks”.Now let us introduce
3 min read
Word Search - Check if a word exists in a grid or not
Given a 2-D grid of characters mat[][] and a string word, the task is to check if that word exist in the grid mat[][] or not. A word can be matched in 4 directions at any point. The 4 directions are horizontally left and right, vertically up and down. Examples: Input: mat[][] = { {'a', 'x', 'm', 'y'}, {'b', 'g', 'd', 'f'}, {'x', 'e', 'e', 't'}, {'r
11 min read
Longest Common Prefix using Word by Word Matching
Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return "". Examples: Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: "gee"Explanation: “gee” is the longest common prefix in all the given strings: "ge
5 min read
Check if permutation of one string can break permutation of another
Given two strings str1 and str2, the task is to check if any permutation of the given strings str1 and str2 is possible such that the character at each index of one string is greater than or equal to the other string. Examples: Input: A = "abc", B = "xya" Output: Yes Explanation: "ayx" is a permutation of B = "xya" which can break to string "abc" w
6 min read
Program to find the Break Even Point
Given the list of monthly expenditure [Tex]\sum exp [/Tex] of an organization, selling price [Tex]S [/Tex] and the overhead maintenance [Tex]M [/Tex] of each item, the task is to calculate the Break Even Point. Break Even Point refers to the number of items sold in order to neutralize the total expenditure i.e. Overall, neither profit nor loss.Exam
4 min read
Minimize number of cuts required to break N length stick into N unit length sticks
Given an integer N denoting the length of a given stick, the task is to minimize the time required to split the stick into pieces of unit length, given that, a single cut is possible for any portion of stick at any instance of time. Examples: Input: N = 100 Output: 7 Explanation: (100 units) ---> (2 portions of 50 units) ---> (4 portions of 2
5 min read
Break the number N in odd powers of 2
Given a positive integer N. The task is to print the array in decreasing order in which the numbers are odd powers of 2 and the sum of all the numbers in the array is N and the size of the array should be minimum if it is not possible to form the array then print -1. Examples: Input: 18 Output: 8 8 2 Explanation: Array with sum 18 and which consist
9 min read
Recursively break a number in 3 parts to get maximum sum
Given a number n, we can divide it in only three parts n/2, n/3 and n/4 (we will consider only integer part). The task is to find the maximum sum we can make by dividing number in three parts recursively and summing up them together.Examples: Input : n = 12 Output : 13 // We break n = 12 in three parts {12/2, 12/3, 12/4} // = {6, 4, 3}, now current
12 min read
Print all ways to break a string in bracket form
Given a string, find all ways to break the given string in bracket form. Enclose each substring within a parenthesis. Examples: Input : abc Output: (a)(b)(c) (a)(bc) (ab)(c) (abc) Input : abcd Output : (a)(b)(c)(d) (a)(b)(cd) (a)(bc)(d) (a)(bcd) (ab)(c)(d) (ab)(cd) (abc)(d) (abcd) We strongly recommend you to minimize your browser and try this your
4 min read
Break an array into maximum number of sub-arrays such that their averages are same
Given an integer array, the task is to divide the array into the maximum number of sub-arrays such that the averages of all subarrays are the same. If it is not possible to divide, then print "Not possible". Examples: Input : arr[] = {1, 5, 7, 2, 0}; Output : (0 1) (2 4) Subarrays arr[0..1] and arr[2..4] have same average. Input : arr[] = {4, 6, 2,
8 min read
Break the number into three parts
Given a really large number, break it into 3 whole numbers such that they sum up to the original number and count the number of ways to do so. Examples : Input : 3Output : 10The possible combinations where the sumof the numbers is equal to 3 are:0+0+3 = 30+3+0 = 33+0+0 = 30+1+2 = 30+2+1 = 31+0+2 = 31+2+0 = 32+0+1 = 32+1+0 = 31+1+1 = 3Input : 6Outpu
10 min read
Break a number such that sum of maximum divisors of all parts is minimum
We need to split a number n such that sum of maximum divisors of all the parts is minimum. Examples : Input: n = 27 Output: Minimum sum of maximum divisors of parts = 3 Explanation : We can split 27 as follows: 27 = 13 + 11 + 3, Maximum divisor of 13 = 1, 11 = 1, 3 = 1. Answer = 3 (1 + 1 + 1). Input : n = 4 Output: Minimum sum of maximum divisors o
6 min read
Print list items containing all characters of a given word
There is a list of items. Given a specific word, e.g., "sun", print out all the items in list which contain all the characters of "sun". For example if the given word is "sun" and the items are "sunday", "geeksforgeeks", "utensils", ""just" and "sss", then the program should print "sunday" and "utensils". Algorithm: Thanks to geek4u for suggesting
7 min read
Recursively print all sentences that can be formed from list of word lists
Given a list of word lists How to print all sentences possible taking one word from a list at a time via recursion? Example: Input: {{"you", "we"}, {"have", "are"}, {"sleep", "eat", "drink"}} Output: you have sleep you have eat you have drink you are sleep you are eat you are drink we have sleep we have eat we have drink we are sleep we are eat we
7 min read
Next word that does not contain a palindrome and has characters from first k
Given a string and a limit k, find lexicographically next word which contains characters from a set of first K letters of the English alphabet and does not contain a palindrome as it's substring of length more than one. It may be assumed that the input string does not contain a palindromic substring. Examples: Input : s = "cba" k = 4 Output : cbd I
7 min read
Second most repeated word in a sequence in Python
Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. (Considering no two words are the second most repeated, there will be always a single word). Examples: Input : {"aaa", "bbb", "ccc", "bbb", "aaa", "aaa"} Output : bbb Input : {"geeks", "for", "geeks", "for", "geeks", "aaa"} Outp
4 min read
Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure Given a string, Find the 1st repeated word in a string. Examples: Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he We have existing solution for this problem please refer Find the first repeated w
4 min read
Fibonacci Word
Like Fibonacci numbers, a Fibonacci word. is a specific sequence of binary digits (or symbols from any two-letter alphabet). The Fibonacci word is formed by repeated concatenation in the same way that the Fibonacci numbers are formed by repeated addition. But unlike the fibonacci number, Fibonacci word has its first two terms different from each ot
3 min read
Number of ways to arrange a word such that all vowels occur together
Given a word containing vowels and consonants. The task is to find that in how many ways the word can be arranged so that the vowels always come together. Given that the length of the word <10. Examples: Input: str = "geek"Output: 6Ways such that both 'e' comes together are 6 i.e. geek, gkee, kgee, eekg, eegk, keeg Input: str = "corporation"Outp
9 min read
Tribonacci Word
Like Fibonacci word, a Tribonacci word. is a specific sequence of digits. The Tribonacci word is formed by repeated concatenation in the same way that the Fibonacci word is formed by repeated addition. But unlike the fibonacci word, Tribonacci word is formed by repeated addition of last three terms and it has its first three terms different from ea
4 min read
Reverse each word in a linked list node
Given a linked list of strings, we need to reverse each word of the string in the given linked list. Examples: Input: geeksforgeeks a computer science portal for geeks Output: skeegrofskeeg a retupmoc ecneics latrop rof skeeg Input: Publish your own articles on geeksforgeeks Output: hsilbuP ruoy nwo selcitra no skeegrofskeeg Using a loop iterate th
6 min read
Find frequency of each word in a string in Python
Write a python code to find the frequency of each word in a given string. Examples: Input : str[] = "Apple Mango Orange Mango Guava Guava Mango" Output : frequency of Apple is : 1 frequency of Mango is : 3 frequency of Orange is : 1 frequency of Guava is : 2 Input : str = "Train Bus Bus Train Taxi Aeroplane Taxi Bus" Output : frequency of Train is
7 min read
Print longest palindrome word in a sentence
Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other two.Input : Welcome to GeeksforGeeks Output : No Pa
14 min read
Most frequent word in first String which is not present in second String
Given two string 'S1' and 'S2', the task is to return the most frequent (which is used the maximum number of times) word from 'S1' that is not present in 'S2'. If more than one word is possible then print lexicographically smallest among them. Examples: Input: S1 = "geeks for geeks is best place to learn", S2 = "bad place" Output: geeks "geeks" is
7 min read
three90RightbarBannerImg