Javascript solution, Divide and Conquer


  • 0
    var longestCommonPrefix = function(strs) {
        if (strs.length === 0) {
            return '';
        }
    
        if (strs.length === 1) {
            return strs[0];
        }
    
        let half = Math.floor(strs.length/2);
        let a = longestCommonPrefix(strs.slice(0, half));
        let b = longestCommonPrefix(strs.slice(half, strs.length));
    
        let commonStr = '';
        for (let i = 0; i < a.length && i < b.length; i++){
            if (a[i] !== b[i]) {
                break;
            }
            commonStr += a[i];
        }
        return commonStr;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.