Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if the string is a combination of strings in an array using JavaScript
We are required to write a JavaScript function that takes in an array of strings as the first argument and a string as the second argument.
The function should check whether the string specified by second argument can be formed by combining the strings of the array in any possible way.
For example ? If the input array is ?
const arr = ["for","car","keys","forth"];
And the string is ?
const str = "forthcarkeys";
Then the output should be true, because the string is a combination of elements at 3, 1 and 2 indexes of the array.
Example
The code for this will be ?
const arr = ["for","car","keys","forth"];
const str = "forthcarkeys";
const checkPossibility = (str = '', arr = []) => {
let possibilities = arr.reduce(function (r, a) {
let p = str.indexOf(a);
while (p !== -1) {
r.push({ word: a, position: p });
p = str.indexOf(a, p + 1);
}
return r;
}, []);
const findRecursively = (i, t) => {
let s = t.slice(), j;
if (i === possibilities.length) {
return !t.join('');
}
if (possibilities[i].word.split('').every(function (c, j) {
return s[j + possibilities[i].position] !== '';
})) {
for (j = 0; j
Output
true
How It Works
The algorithm works by finding all possible positions where each array string can appear in the target string. It then uses recursion to try different combinations, marking characters as "used" to avoid overlaps. The function returns true if all characters in the target string can be covered by the array strings.
Alternative Approach Using Backtracking
Here's a simpler approach using backtracking:
function canFormString(targetStr, wordArray) {
function backtrack(index) {
if (index === targetStr.length) {
return true;
}
for (let word of wordArray) {
if (targetStr.startsWith(word, index)) {
if (backtrack(index + word.length)) {
return true;
}
}
}
return false;
}
return backtrack(0);
}
const arr = ["for", "car", "keys", "forth"];
const str = "forthcarkeys";
console.log(canFormString(str, arr));
true
Conclusion
Both approaches solve the problem of checking if a string can be formed from an array of strings. The backtracking method is more straightforward and easier to understand, while the original approach handles overlapping substrings more comprehensively.
