14. Longest Common Prefix — JavaScript Solution — by Abu Saleh Faysal

Abu Saleh Faysal
2 min readJan 20, 2023

After seeing the problem, I determined that iterating the first element of the array and iterating the whole array could be a straightforward approach to solving this problem.

Solution:

Step 01: declare a variable named “prefix” and set the initial value as an empty string(“”).
Step 02: Check if the given array length is 0 or if the given array is null. If it meets this condition, return the prefix which is an empty string.
Step 03: If the given array does not meet the previous condition, iterate the first element of the array using a for loop and store the elements in the “char” variable.
Step 04: Using another for loop, iterate the given array and this time start the iteration from the second index of the array.
Step 05: If the char and the second element of the given array’s char is not equal, then return the prefix.
Step 06: After the second iteration, add the char with the prefix.
Step 07: Return the prefix.

Runtime: 93 ms
Memory: 42.9 MB

/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
let prefix = "";

if(strs.length === 0 || strs === null) return prefix;

for(let i = 0; i < strs[0].length; i++) {
let char = strs[0][i];
for(let j = 1; j < strs.length; j++) {
if(char !== strs[j][i]) {
return prefix;
}
}
prefix += char;
}

return prefix;
};

👉 Support me: https://www.buymeacoffee.com/abusalehfaysal

👉 YouTube Channel: https://www.youtube.com/channel/UCW_09Nbobf4URLkAlEo84sw

👉 PlayList Link: https://youtube.com/playlist?list=PLUnklBXn8NSefCpBaLe39mds6dQx-tDDD

👉 Connect with me (LinkedIn): https://www.linkedin.com/in/abusalehfaysal

👉 Follow our LinkedIn Page: https://www.linkedin.com/company/thebacklogprogrammer/

👉 Like our Facebook page: https://www.facebook.com/thebacklogprogrammer/

👉 Join our community (Facebook group): https://www.facebook.com/groups/5500588936676942/

👉 Follow me at: https://www.facebook.com/AbuSalehFaysal10

👉 Twitter: https://twitter.com/AbuSalehFaysal

👉 Abu Saleh Faysal’s Blog: https://abusalehfaysal.hashnode.dev/

👉 Hasnode: https://hashnode.com/@AbuSalehFaysal

👉 Dev Community: https://dev.to/abusalehfaysal

👉 freeCodeCamp: https://www.freecodecamp.org/abusalehfaysal

👉 Medium: https://abusalehfaysal.medium.com/

👉 GitHub: https://github.com/AbuSalehFaysal
👉 GitLab: https://gitlab.com/AbuSalehFaysal

--

--

Abu Saleh Faysal

Software Engineer at Onethread | Front-End Developer | Blockchain Enthusiast | JavaScript | TypeScript | React | Redux