“Longest Common Prefix” cheat sheet Javascript solution

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:

Example:

Explanation:

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:

--

--

Lifelong learner , Full Stack Software Engineer.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store