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
Dynamic programming to check dynamic behavior of an array in JavaScript
We are required to write a JavaScript function that takes in an array of strings, ordered by ascending length.
The function should return true if, for each pair of consecutive strings, the second string can be formed from the first by adding a single letter either at the beginning or end.
For example: If the array is given by ?
const arr = ["c", "ca", "can", "acan", "acane", "dacane"];
Then our function should return true because:
- "ca" = "c" + "a" (adding "a" at the end)
- "can" = "ca" + "n" (adding "n" at the end)
- "acan" = "a" + "can" (adding "a" at the beginning)
- "acane" = "acan" + "e" (adding "e" at the end)
- "dacane" = "d" + "acane" (adding "d" at the beginning)
Example
The code for this will be ?
const arr = ["c", "ca", "can", "acan", "acane", "dacane"];
const isProgressive = arr => {
for(let i = 0; i < arr.length-1; i++){
const current = arr[i];
const next = arr[i+1];
const nextLength = next.length;
// Check if next string is current + one char at end OR one char at start + current
if(next === current + next[nextLength-1] || next === next[0] + current){
continue;
}
return false;
}
return true;
};
console.log(isProgressive(arr));
Output
true
How It Works
The algorithm iterates through consecutive pairs of strings and checks two conditions:
-
Addition at the end:
next === current + next[nextLength-1]- checks if the next string equals the current string plus its last character -
Addition at the beginning:
next === next[0] + current- checks if the next string equals its first character plus the current string
If any pair fails both conditions, the function returns false. Otherwise, it returns true.
Testing with Different Arrays
// Test case 1: Valid progressive array
const arr1 = ["a", "ab", "abc", "abcd"];
console.log("Test 1:", isProgressive(arr1));
// Test case 2: Invalid progressive array
const arr2 = ["a", "ab", "xyz", "xyza"];
console.log("Test 2:", isProgressive(arr2));
// Test case 3: Mixed additions (beginning and end)
const arr3 = ["x", "xx", "xxx", "axxx"];
console.log("Test 3:", isProgressive(arr3));
Test 1: true Test 2: false Test 3: true
Conclusion
This dynamic programming approach efficiently checks if an array follows a progressive pattern by validating that each string can be formed from the previous one by adding exactly one character at either end. The solution has O(n) time complexity where n is the array length.
