DEV Community

Discussion on: Finding the Longest Common Prefix

Collapse
 
salyadav profile image
Saloni Yadav

a slight alternative. Not sure whether the approaches have a different time complexity or not. You could help me with that?

var longestCommonPrefix = function(strs) {
    if(strs.length==0)
        return "";
    let pre = strs[0];
    var newpre = '';
    for (s of strs) {
        newpre='';
        for (let i=0; i<Math.min(s.length, pre.length); i++) {
            if (s[i]==pre[i]) {
                newpre+=s[i];
            } else {
                break;
            }
        }
        pre = newpre;
    }
    return newpre;
};
Enter fullscreen mode Exit fullscreen mode