Home > Blockchain >  leetcode #14 same test case but wrong result?
leetcode #14 same test case but wrong result?

Time:07-07

Ex1) Input: strs = ["flower","flow","flight"] Output: "fl"

Ex2) Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.

My code is right for those two examples and for this testcase below: Input: ["ab", "a"] Output: "" Expected: "a"

I get this but it runs well when I set the same test case on leetcode and also when I ran on vscode.

this is my code:

var flag = false;

 var longestCommonPrefix = function(strs) {
    if(strs.length==1)
        return strs[0];

    strs.sort(function(a,b){
        return a.length - b.length;
    });
    
    var str = ""
    for(var i=0; i<strs[0].length; i  ){
        for(var j=0; j<strs.length; j  ){
            if(strs[0][i] != strs[j][i]){
                flag = true;
                break;
            }
        }
        if(flag)
            break;
        str  = strs[0][i];
    }
    return str;
};

console.log(longestCommonPrefix(["ab", "a"]));

CodePudding user response:

Your flag is declared outside the function. This means that if the function is called multiple times, if the first invocation sets it to true, the second invocation, it will be seen as true from the beginning.

You won't see it as a problem if you only call the function once, but you will (and LeetCode will) if called for multiple test cases.

var flag = false;

var longestCommonPrefix = function(strs) {
  if (strs.length == 1)
    return strs[0];

  strs.sort(function(a, b) {
    return a.length - b.length;
  });

  var str = ""
  for (var i = 0; i < strs[0].length; i  ) {
    for (var j = 0; j < strs.length; j  ) {
      if (strs[0][i] != strs[j][i]) {
        flag = true;
        break;
      }
    }
    if (flag)
      break;
    str  = strs[0][i];
  }
  return str;
};

console.log(longestCommonPrefix(["flower","flow","flight"]));
console.log(longestCommonPrefix(["ab", "a"]));

Move the flag inside the function so that starts out as false every time the function is called anew.

var longestCommonPrefix = function(strs) {
  let flag = false;
  // etc

var longestCommonPrefix = function(strs) {
  let flag = false;
  if (strs.length == 1)
    return strs[0];

  strs.sort(function(a, b) {
    return a.length - b.length;
  });

  var str = ""
  for (var i = 0; i < strs[0].length; i  ) {
    for (var j = 0; j < strs.length; j  ) {
      if (strs[0][i] != strs[j][i]) {
        flag = true;
        break;
      }
    }
    if (flag)
      break;
    str  = strs[0][i];
  }
  return str;
};

console.log(longestCommonPrefix(["flower","flow","flight"]));
console.log(longestCommonPrefix(["ab", "a"]));

  • Related