0

I sorted the elements and comparing the first and last string to check the common prefixes. It works for most of the cases, but not for the input ["dog","racecar","car"]. The expected output is "", but what I'm getting is "c" (The "r" in "car" and "r" in "racecar"). I can tell the code to remove the last char, but this will break the other cases such as ["car", "car", "car"]. Not sure what am I missing. Any insights would help me improve.

Thanks

var longestCommonPrefix = function(strs) {
 let count=0
   const sortedString = strs.sort()
   const firstString = sortedString[0]
   const lastString = sortedString[sortedString.length-1]
   for(let i=0; i< firstString.length; i++) {
       if(firstString.charAt(i) === lastString.charAt(i)) {
           count++
       }
   }
    
 console.log(firstString.substring(0, count))
};

longestCommonPrefix(
  ["dog","racecar","car"])

1
  • "I'm solving Leetcode problem: 14 using Javascript" tells us nothing about the nature of the problem. Consider rephasing your question to describe the actual problem. Make sure we have enough info to help you. The question should stand on it's own so we don't need to know anything about Leetcode or this particular "problem" Commented Aug 29, 2022 at 4:38

1 Answer 1

2

You need to break out of the loop as soon as a match is not found. Otherwise, for example, ra and ca match on the second index, the a - which is undesirable.

var longestCommonPrefix = function(strs) {
  let count = 0
  const sortedString = strs.sort()
  const firstString = sortedString[0]
  const lastString = sortedString[sortedString.length - 1]
  for (let i = 0; i < firstString.length; i++) {
    if (firstString.charAt(i) === lastString.charAt(i)) {
      count++
    } else {
      break;
    }
  }
  console.log(firstString.substring(0, count))
};

longestCommonPrefix(
  ["dog", "racecar", "car"])

or, refactored a bit

const longestCommonPrefix = (strs) => {
  strs.sort();
  const firstString = strs[0];
  const lastString = strs[strs.length - 1];
  let prefixSoFar = '';
  for (let i = 0; i < firstString.length; i++) {
    if (firstString[i] === lastString[i]) {
      prefixSoFar += firstString[i];
    } else {
      return prefixSoFar;
    }
  }
  return prefixSoFar;
};

console.log(longestCommonPrefix(["dog", "racecar", "car"]));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.