I just recently finished the following problem on Leetcode problem. I know it's not the cleanest or fastest solution. I would appreciate if I can get some feedback on how to optimize the code.
The idea is too add all possible prefixes into an array and return the longest possible prefix. I believe this is probably why the algorithm doesn't run as fast as it should.
Also, I would appreciate if someone can assist in determining what the space and time complexity would be for the algorithm below?
var longestCommonPrefix = function(strs) {
const firstWord = strs[0];
const arrResults = [];
let index = 1;
let arrWithoutFirstElement = strs.slice(1, strs.length);
if(strs.length===0)return '';
if(strs.length===1)return strs[0];
while(index <= firstWord.length) {
if(arrWithoutFirstElement.every(element =>
element.substring(0,index)===firstWord.substring(0,index))){
arrResults.push(firstWord.substring(0,index));
}
index++;
}
return arrResults.length > 0 ? arrResults[arrResults.length-1] : '';
}
console.log(longestCommonPrefix(["flower","flow","flight"]));