'leetcode 14. Longest Common Prefix Javascript
[leetcode problem 14][1] Not understanding why the output is rejected for Longest Common Prefix. Not pasting in the code submission as the problem is my misreading the question.
Wrong Answer
Details
Input
["reflower","flow","flight"]
Output
"fl"
Expected
""
Description copied from site :
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.
Solution 1:[1]
As the problem goes:
... find the longest common prefix string...
You need to find the longest common prefix - which is the string at the beginning of each word.
In your case, the input is ["reflower","flow","flight"].
While flow and flight have the same prefix - fl, reflower doesn't have the same prefix (since it does not start with fl but with re), and as a result the whole 3 words doesn't have a common prefix so the output should be "".
Solution 2:[2]
const longestCommonPrefix = function(strs) {
// const strs = ["flower","flow","flight"];
// console.log(strs);
if (!strs.length) return "";
for (let i = 0; i <= strs[0]; i++) {
if (!strs.every((string) => string[i] === strs[0][i])) {
return strs[0].slice(0, i);
}
}
return strs[0].slice();
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Omri Attiya |
| Solution 2 | Sebastian Simon |
