“Longest Common Prefix” cheat sheet Javascript solution

Fadi Tillman
2 min readJun 12, 2021

The Longest Common Prefix challenge is in the easy category and is a good start for understanding more challenging algorithms. I will focus on explaining a solution that works and not on the O time and space complexity.

Challenge:

“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 “”. LeetCode

Note:

//Find longest equal prefix// Array of strings//Return “” if empty//Prefix will always start at the beginning of the string

Example:

string = [“pot”, “pop”, “top”]return “”string = [“flower”,” flow”,” floor”]return “flo”

Explanation:

//Loop through the array of substrings compares each of the characters at a similar index, //starting from the beginning and increment //until different //then return the longest prefix.

1.Prefix start as an empty string
longestPrefix = “”

2.If there is no common prefix, return an empty string “”. LeetCode

if (strs.length === 0) return longestPrefix

return longestPrefix

3.Loop through substrings characters starting from the first character of the first substring

for (let i = 0; i < strs[0].length; i++){

for (let j = 0; j < strs.length; j++){

4.Compare each character of the array substrings at a similar index and increment through characters until not equal

const currentChar = strs[0][i]

if (strs[j][i] !== currentChar) return longestPrefix

5.return the longest prefix

longestPrefix += currentChar

Solution:

var longestCommonPrefix = function(strs) {longestPrefix = “”if (strs.length === 0) return longestPrefixfor (let i = 0; i < strs[0].length; i++){const currentChar = strs[0][i]for (let j = 0; j < strs.length; j++){if (strs[j][i] !== currentChar) return longestPrefix}longestPrefix += currentChar}return longestPrefix};

--

--