Skip to main content

LeetCode 14 - Longest Common Prefix

  • Difficulty: Easy.
  • Related Topics: String.
  • Link: leetcode

Problem

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

Solution 1

/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function (strs) {
for (let i = 0; i < strs[0].length; i++) {
for (let j = 1; j < strs.length; j++) {
if (strs[0][i] !== strs[j][i]) {
return strs[0].slice(0, i);
}
}
}
return strs[0];
};

Solution 2

var longestCommonPrefix = function (strs) {
let prefix = strs[0];

for (let i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.substring(0, prefix.length - 1);
}
}
return prefix;
};

Complexity:

  • Time complexity : O(n^2).
  • Space complexity : O(1).