Open In App

JavaScript Program for Word Break Problem

Last Updated : 05 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The word break problem is a well-known and fundamental challenge within the field of computer science. The Word Break Problem in JavaScript involves determining if a given string can be segmented into words from a dictionary. It seeks to find a valid combination of dictionary words that compose the entire input string. In this context, a ‘word’ is defined as a consecutive sequence of characters separated by spaces. Meanwhile, the ‘dictionary’ is represented as a collection of valid words.

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Recursive approach

In this approach, we are using for in loop. The recursive function canWordBreak checks if a given string can be segmented into words from a dictionary. It iteratively slices the input string, checking if the substring exists in the dictionary. If found, it recursively calls itself on the remaining portion of the string. When an empty string is reached, it returns true, indicating success. The function backtracks if no valid segmentation is found and returns false if no valid segmentation exists.

Example: In this example we are using the above-explained approach.

Javascript




function canWordBreak(string, dictionary, result = []) {
    if (string === "") {
        return result;
    }
  
    for (let i in string) {
        const substring = 
            string.slice(0, parseInt(i) + 1);
        if (dictionary.includes(substring)) {
            const remainingString = 
                string.slice(parseInt(i) + 1);
            const wordSegment = 
                canWordBreak(remainingString, 
                    dictionary, [...result, substring]);
            if (wordSegment !== null) {
                return wordSegment;
            }
        }
    }
  
    return null;
}
  
let dictionary = ["geeks", "for", "forgeeks"];
let string = "geeksforgeeks";
let result = canWordBreak(string, dictionary);
  
if (result !== null) {
    console.log(result.join(" "));
} else {
    console.log("String cannot be broken.");
}


Output

geeks for geeks

Approach 2: Dynamic programming

In this approach, we are using dynamic programming to check if a string can be segmented into words from a dictionary. It creates an array to store whether substrings are valid and iterates through the string and dictionary. If a valid segmentation is found, it returns true, otherwise false.

Example: Using dynamic programming, the code creates an array arr of size n + 1. It iterates through i and j to check if substrings from j to i exist in the dictionary, setting arr[i] to true if found, allowing it to determine if the input string can be segmented into words.

Javascript




function wordBreak(string, dictionary) {
    const n = string.length;
    const arr = new Array(n + 1).fill(false);
    arr[0] = true;
  
    for (let i = 1; i <= n; i++) {
        for (let j in arr) {
            const subString = string.slice(parseInt(j), i);
            arr[i] = arr[j] && dictionary.includes(
                subString) ? true : arr[i];
        }
    }
  
    return arr[n];
}
  
const dictionary = ["Geeks", "forGeeks"];
const inputString = "GeeksforGeeks";
const result = wordBreak(inputString, dictionary);
console.log(result);


Output

true


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads