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
Longest string consisting of n consecutive strings in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of strings. Our function should create combinations by combining all possible n consecutive strings in the array and return the longest such string that comes first.
Example
Following is the code ?
const arr = ["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"];
const num = 2;
function longestConsec(strarr, k) {
if (strarr.length == 0 || k > strarr.length || k <= 0) return '';
let longStr = '';
let newStr = '';
for (let i = 0; i < strarr.length; i++) {
newStr = strarr.slice(i, i + k);
if (newStr.join('').length > longStr.length) {
longStr = newStr.join('');
}
}
return longStr;
}
console.log(longestConsec(arr, num));
abigailtheta
How It Works
The function iterates through the array, taking slices of k consecutive elements. For each slice, it joins the strings together and compares the length with the current longest string. If a longer combination is found, it becomes the new longest string.
Step-by-Step Breakdown
const strings = ["abc", "defgh", "ij", "klmno"];
const k = 3;
function longestConsecWithSteps(strarr, k) {
console.log(`Input array: [${strarr.join(', ')}]`);
console.log(`Looking for ${k} consecutive strings`);
if (strarr.length == 0 || k > strarr.length || k <= 0) return '';
let longStr = '';
for (let i = 0; i <= strarr.length - k; i++) {
let slice = strarr.slice(i, i + k);
let combined = slice.join('');
console.log(`Position ${i}: [${slice.join(', ')}] -> "${combined}" (length: ${combined.length})`);
if (combined.length > longStr.length) {
longStr = combined;
console.log(`New longest: "${longStr}"`);
}
}
return longStr;
}
console.log("Result:", longestConsecWithSteps(strings, k));
Input array: [abc, defgh, ij, klmno] Looking for 3 consecutive strings Position 0: [abc, defgh, ij] -> "abcdefghij" (length: 10) New longest: "abcdefghij" Position 1: [defgh, ij, klmno] -> "defghijklmno" (length: 12) New longest: "defghijklmno" Result: defghijklmno
Edge Cases
// Empty array console.log(longestConsec([], 2)); // "" // k greater than array length console.log(longestConsec(["a", "b"], 3)); // "" // k equals 0 or negative console.log(longestConsec(["a", "b", "c"], 0)); // "" // Single element with k=1 console.log(longestConsec(["hello"], 1)); // "hello"
hello
Conclusion
This algorithm efficiently finds the longest concatenated string from n consecutive elements by iterating through all possible combinations and tracking the longest one. The time complexity is O(n*k) where n is the array length and k is the number of consecutive elements.
