DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 14. Longest Common Prefix

Javascript Code

Considering the first word as a whole as prefix ;

we iterate for a mismatch and then trim at that point

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

    if (!strs.length) return "";

    let prefix = strs[0]; 

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

        if (!strs.every(word => word[i] === char)) {
            return prefix.slice(0, i); 
        }
    }

    return prefix;
};


Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay