Skip to content

Instantly share code, notes, and snippets.

@ArataKagan
Created August 4, 2019 07:52
Show Gist options
  • Save ArataKagan/cec6395e7b8fe74bbc9cb4274c4337d0 to your computer and use it in GitHub Desktop.
Save ArataKagan/cec6395e7b8fe74bbc9cb4274c4337d0 to your computer and use it in GitHub Desktop.
var longestCommonPrefix = function(strs) {
var common = "";
var index = 0;
if(strs.length == 0 || strs == "null"){
return common;
}
// split the first string of strs
var string = strs[0].split("");
// Loop over the stored string's letter
for(let i=0; string.length > i; i++){
var letter = string[i];
// Loop over the rest of the strings and compare the same indexies of each string
for(let j=1; strs.length > j; j++){
if(letter != strs[j].charAt(index) || index > strs[j].length){
return common;
}
}
common += letter;
index++;
}
return common;
};
longestCommonPrefix(["flower","flow","flight"]) // return "fl"
@ArataKagan
Copy link
Author

Coding practice from Leet Code's "Longest Common Prefix" question.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment