JavaScript Program for Word Break Problem
Last Updated :
28 Apr, 2025
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.");
}
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);
Similar Reads
JavaScript Program to Print the First Letter of Each Word Printing the first letter of each word involves extracting the initial character from every word in a given string, typically accomplished by splitting the string into words and selecting the first character from each resulting word. Examples of Printing the First Letter of Each Word Table of Conten
3 min read
JavaScript Program to find Lexicographically next String In this article, we are going to learn how can we find the Lexicographically next string. Lexicographically next string refers to finding the string that follows a given string in a dictionary or alphabetical order.Examples: Input : testOutput : tesuExplanation : The last character 't' is changed to
3 min read
Split a Sentence into Fixed-Length Blocks without Breaking Words in JavaScript Given a sentence, our task is to split it into blocks of a fixed length without breaking words using JavaScript.Example:Input: Sentence= "This is a sample sentence to demonstrate splitting into blocks without breaking words.", blocksize = 15Output:Blocks: [ 'This is a', 'sample sentence ', 'to demon
3 min read
Primer CSS Typography Word-Break Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by
2 min read
Java Program to Replace All Line Breaks from Strings Given a string, write a Java program to replace all line breaks from the given String. Examples Input - Geeks For Geeks Output - Geeks For Geeks Line Break: A line break ("\n") is a single character that defines the line change. In order to replace all line breaks from strings replace() function can
2 min read
CSS word-break Property This word-break property is used to specify how to break the word when the word reaches the end of the line. The line breaks in the text can occur in certain spaces, like when there is a space or a hyphen.Syntax:Â Â word-break: normal|break-all|keep-all|break-word|initial|inherit;Default Value: Normal
3 min read