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.

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

πŸ‘‰ 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

Top comments (0)