Skip to main content

Leetcode - 14. Longest Common Prefix

· One min read

https://leetcode.com/problems/longest-common-prefix/

Solution 1

/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
if (strs.length === 1) {
return strs[0];
}

const [baseWord, ...rest] = strs;

for (let i = 0; i <= baseWord.length; i++) {
for (let j = 0; j < strs.length; j++) {
if (baseWord[i] !== strs[j][i]) {
return baseWord.slice(0, i);
}
}
}

return baseWord;
};

Runtime: 116 ms, faster than 25.96% of JavaScript online submissions for Longest Common Prefix.

Memory Usage: 42.6 MB, less than 52.34% of JavaScript online submissions for Longest Common Prefix.

Solution 2

/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
if (!strs.length) {
return '';
}

for (let i = 0; i <= strs[0].length; i++) {
if (!strs.every((string) => string[i] === strs[0][i])) {
return strs[0].slice(0, i);
}
}

return strs[0];
};

Runtime: 85 ms, faster than 77.67% of JavaScript online submissions for Longest Common Prefix.

Memory Usage: 43.1 MB, less than 34.02% of JavaScript online submissions for Longest Common Prefix.