DEV Community

Cover image for 14. Longest Common Prefix - JavaScript Solution - by Abu Saleh Faysal
Abu Saleh Faysal
Abu Saleh Faysal

Posted on

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

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.


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;
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Support me:

πŸ‘‰ YouTube Channel:

πŸ‘‰ PlayList Link:

πŸ‘‰ Connect with me (LinkedIn):

πŸ‘‰ Follow our LinkedIn Page:

πŸ‘‰ Like our Facebook page:

πŸ‘‰ Join our community (Facebook group):

πŸ‘‰ Follow me at:

πŸ‘‰ Twitter:

πŸ‘‰ Abu Saleh Faysal’s Blog:

πŸ‘‰ Hasnode:

πŸ‘‰ Dev Community:

πŸ‘‰ freeCodeCamp:

πŸ‘‰ Medium:

πŸ‘‰ GitHub:
πŸ‘‰ GitLab:

Top comments (0)

Visualizing Promises and Async/Await 🀯

async await

☝️ Check out this all-time classic DEV post