I have made a function for finding the longest common prefix for the challenge on the leetcode site. This is the code:
var longestCommonPrefix = function(strs) {
let longestPrefix = '';
if (strs.length > 0) {
longestPrefix = strs[0];
for (let i = 1; i < strs.length; i++) {
for (let j = 0; j < longestPrefix.length; j++) {
if (strs[i][j] != longestPrefix[j]) {
longestPrefix = longestPrefix.slice(0, j);
break;
}
}
}
}
return longestPrefix;
};
I am sure there is a way to make this code better, but not sure how to do that. Would appreciate any help.