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
Checking progressive array - 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.
How It Works
The algorithm checks each consecutive pair of strings to verify that the longer string can be formed by adding exactly one character to either the beginning or end of the shorter string.
Example
Following is the code ?
const arr = ["c", "ca", "can", "acan", "acane", "dacane"];
const isProgressive = arr => {
for(let i = 0; i < arr.length-1; i++){
const nextLength = arr[i+1].length;
if(arr[i+1] === arr[i+1][0] + arr[i] || arr[i+1] === arr[i] + arr[i+1][nextLength-1] ){
continue;
};
return false;
};
return true;
};
console.log(isProgressive(arr));
Output
Following is the output in the console ?
true
Step-by-Step Analysis
Let's trace through the example array to understand how the function works:
const arr = ["c", "ca", "can", "acan", "acane", "dacane"];
// Check each transition:
console.log("c" + "a" === "ca"); // true (add 'a' at end)
console.log("a" + "can" === "acan"); // true (add 'a' at beginning)
console.log("acan" + "e" === "acane"); // true (add 'e' at end)
console.log("d" + "acane" === "dacane"); // true (add 'd' at beginning)
true true true true
Alternative Implementation
Here's a cleaner version that's easier to understand:
const isProgressiveArray = (arr) => {
for(let i = 0; i < arr.length - 1; i++){
const current = arr[i];
const next = arr[i + 1];
// Check if next string is formed by adding one char at beginning or end
const addedAtEnd = next === current + next[next.length - 1];
const addedAtStart = next === next[0] + current;
if(!addedAtEnd && !addedAtStart){
return false;
}
}
return true;
};
// Test cases
console.log(isProgressiveArray(["a", "ab", "abc"])); // true
console.log(isProgressiveArray(["x", "yx", "zyx"])); // true
console.log(isProgressiveArray(["a", "ab", "xyz"])); // false
true true false
Conclusion
A progressive array requires each string to be formed by adding exactly one character to the previous string. The function efficiently validates this by checking both possible positions (beginning or end) for each consecutive pair.
