Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created November 11, 2024 06:11
Show Gist options
  • Save sAVItar02/aef74f0a54cba69d40a412f85bc3db10 to your computer and use it in GitHub Desktop.
Save sAVItar02/aef74f0a54cba69d40a412f85bc3db10 to your computer and use it in GitHub Desktop.
Longest Common Prefix
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if(strs.length == 0) return "";
if(strs.length == 1) return strs[0];
let prefix = strs[0];
let prefixLen = prefix.length;
for(let i=1; i<strs.length; i++) {
while(prefix != strs[i].slice(0, prefixLen)) {
prefixLen -= 1;
if(prefixLen == 0) return "";
prefix = prefix.slice(0, prefixLen);
}
}
return prefix;
};
// store the first element as a prefix check
// run a loop through the array and check whether the current prefix string equals the string in current iteration
// if not, then remove the last character from both the strings and check again
// do this till either the strings become empty or we find a match
// if the strings are empty return empty string because there is no longest common prefix
// if we find a match, store it as the new prefix and move on to the next iteration
// finally return the prefix after the loop is done
// Time: O(n * m) n --> length of array; m --> length of first string in the array
// Space: O(m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment