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

Word Break Problem | DP-32

Last Updated : 17 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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 word can be broken
// down into words from the wordList
bool WordBreak(const vector<string>& wordList,
               const string& word)
{
    // If the word is empty, it can be broken down into
    // an empty list of words
    if (word.empty())
        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.substr(0, i);

        if (find(wordList.begin(), wordList.end(), prefix)
                != wordList.end()
            && WordBreak(wordList, word.substr(i))) {
            return true;
        }
    }

    return false;
}

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

    bool result = WordBreak(wordList, "ilikesamsung");

    cout << boolalpha << result << endl; // Output: true

    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
true


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
// A Dynamic Programming based program to test whether a given string can
// be segmented into space separated words in dictionary
#include <iostream>
#include <string.h>
using namespace std;

/* 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*/
int dictionaryContains(string word)
{
    string dictionary[] = {"mobile","samsung","sam","sung","man","mango",
                           "icecream","and","go","i","like","ice","cream"};
    int size = sizeof(dictionary)/sizeof(dictionary[0]);
    for (int i = 0; i < size; i++)
        if (dictionary[i].compare(word) == 0)
           return true;
    return false;
}

// Returns true if string can be segmented into space separated
// words, otherwise returns false
bool wordBreak(string str)
{
    int size = str.size();
    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[size+1];
    memset(wb, 0, sizeof(wb)); // Initialize all values as false.

    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.substr(0, i)"
        if (wb[i] == false && dictionaryContains( str.substr(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.substr(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++)
        cout << " " << wb[i]; */

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

// Driver program to test above functions
int main()
{
    wordBreak("ilikesamsung")? cout <<"Yes\n": cout << "No\n";
    wordBreak("iiiiiiii")? cout <<"Yes\n": cout << "No\n";
    wordBreak("")? cout <<"Yes\n": cout << "No\n";
    wordBreak("ilikelikeimangoiii")? cout <<"Yes\n": cout << "No\n";
    wordBreak("samsungandmango")? cout <<"Yes\n": cout << "No\n";
    wordBreak("samsungandmangok")? cout <<"Yes\n": cout << "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

The time complexity of the given implementation of the wordBreak function is O(n^3), where n is the length of the input string.

The auxiliary space of the implementation is O(n), as an extra boolean array of size n+1 is created.

Optimized Dynamic Programming: 
In this approach, apart from the dp table, we also maintain all the indexes which have matched earlier. Then we will check the substrings from those indexes to the current index. If anyone of that matches then we can divide the string up to that index.
In this program, we are using some extra space. However, its time complexity is O(n*n) if n>s or O(n*s) if s>n  where s is the length of the largest string in the dictionary and n is the length of the given string. 

C++
// A Dynamic Programming based program to test
// whether a given string can  be segmented into
// space separated words in dictionary
#include <bits/stdc++.h>
using namespace std;

/* 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*/
int dictionaryContains(string word)
{
    string dictionary[]
        = { "mobile", "samsung",  "sam",  "sung", "man",
            "mango",  "icecream", "and",  "go",   "i",
            "like",   "ice",      "cream" };
    int size = sizeof(dictionary) / sizeof(dictionary[0]);
    for (int i = 0; i < size; i++)
        if (dictionary[i].compare(word) == 0)
            return true;
    return false;
}

// Returns true if string can be segmented into space
// separated words, otherwise returns false
bool wordBreak(string s)
{
    int n = s.size();
    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.
    vector<bool> dp(n + 1, 0); // Initialize all values
    // as false.

    // matched_index array represents the indexes for which
    // dp[i] is true. Initially only -1 element is present
    // in this array.
    vector<int> matched_index;
    matched_index.push_back(-1);

    for (int i = 0; i < n; i++) {
        int msize = matched_index.size();

        // 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
            // matched_index[j]
            // + 1  and of length i - matched_index[j]
            string sb = s.substr(matched_index[j] + 1,
                                 i - matched_index[j]);

            if (dictionaryContains(sb)) {
                f = 1;
                break;
            }
        }

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

// Driver code
int main()
{
    wordBreak("ilikesamsung") ? cout << "Yes\n"
                              : cout << "No\n";
    wordBreak("iiiiiiii") ? cout << "Yes\n"
                          : cout << "No\n";
    wordBreak("") ? cout << "Yes\n" : cout << "No\n";
    wordBreak("ilikelikeimangoiii") ? cout << "Yes\n"
                                    : cout << "No\n";
    wordBreak("samsungandmango") ? cout << "Yes\n"
                                 : cout << "No\n";
    wordBreak("samsungandmangok") ? cout << "Yes\n"
                                  : cout << "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
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" Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks
3 min read
Search a Word in a 2D Grid of characters (Word Search)
Given a 2D grid of characters and a single word/an array of words, find all occurrences of the given word/words in the grid. A word can be matched in all 8 directions at any point. Word is said to be found in a direction if all characters match in this direction (not in zig-zag form).The 8 directions are, Horizontally Left, Horizontally Right, Vert
15+ min read
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"Recommended PracticeLongest Common Prefix in an ArrayTry It! We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest co
15 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
Word Wrap Problem
Given an array words[] of size n, where words[i] denotes the number of characters in one word. Let K be the limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly. Assume that the length of each word is smaller than the line width. When line breaks are
9 min read
three90RightbarBannerImg