Problem Statement
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 "".
Algorithm
if array is empty, return a prefix of empty string Or if
array has 1 word, return the whole word.Iterate through letter of first word of Array , and compare
those letters to same Indexed letter to other world.
Example
let strs = ["flower","flow","flight"]
So What above line meaning is -
str[0][0] === str[1][0],
str[0][1] === str[1][1] and so on....
if the letters match continue to next set of letters
otherwise return the prefixIf the letter is no longer matching then the first word
will mark where the longest common prefix is, so
we add to our empty string.
First Try to Solve Problem using Algorithm
Javascript Function for Longest Common Prefix
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
let result = "";
//array is empty, return a prefix of empty string
if (strs.length === 0) {return ""}
//array has 1 word, return the whole word
if (strs.length === 1) {return strs[0]}
//Iterate through letter of first word of Array
for(let i=0 ; i<strs[0].length ; i++){
//compare those letters to same Indexed letter to other world.
for(let j=1 ; j< strs.length ; j++){
if(strs[0][i] == strs[j][i]){
continue;
}else{
return result
}
}
/*If the letter is no longer matching then the first word
will mark where the longest common prefix is, so
we add to our empty string*/
result += strs[0][i];
}
return result;
};
Test Cases
Input: strs = ["flower","flow","flight"]
Output: "fl"
Input: strs = ["dog","racecar","car"]
Output: ""
Input: strs = ["",""]
Output: ""
Top comments (3)
Nice.
It would be great if you added the question to the article for context.
👍
Added Problem Statement to the article @orimdominic . for more clarity you can visit
leetcode.com/problems/longest-comm...