Javascript 12 lines, O(n*m) vertical scanning solution

  • 0

    think of the input as 2D array
    `_ _ _ _
    | a b b c
    | a b e
    | a b

    scan each column left to right. append i'th column char before incrementing. return answer if there's an empty string or if there's undefined or if there's a different character.

    var longestCommonPrefix = (strs) => {
      if(strs[0]===''||strs.length===0) return '';
      let ans = '';
      for(let i=0; i<strs[0].length; i++){
        let curChar = strs[0][i];
        for(let j=0; j<strs.length; j++)
          if(strs[j][i]!==curChar || !strs[j][i] || strs[j]==='') return ans;
      return ans;

    runtime: O(n * m) where m is the length of the shortest string in the input

Log in to reply

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