Popular interviews 150
The longest common prefix problem is a classic string manipulation challenge that tests your ability to identify shared patterns between strings. Let’s break it down LeetCode 14: Longest common prefix And solve it with JavaScript.
🚀 Problem description
Given an array of strings strs
returns the longest common prefix among all strings in the array.
If there is no common prefix, an empty string is returned ""
.
💡 Example
Example 1
Input: strs = ["flower","flow","flight"]
Output: "fl"
Explanation: The first two letters "fl" are common to all strings.
Example 2
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: No common prefix exists among the input strings.
🏆 JavaScript solution
We will use a horizontal scan method to iteratively compare the prefix of one string to the next string to update the common prefix.
implement
var longestCommonPrefix = function(strs) {
if (!strs.length) return "";
let prefix = strs[0];
for (let i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) !== 0) {
prefix = prefix.slice(0, -1);
if (prefix === "") return "";
}
}
return prefix;
};
🔍 How it works
-
Starting from the first string:
- Use the first string as the initial prefix.
-
Iterate over a string:
- Compares the current prefix to each string.
- If the prefix does not match the beginning of the string, shorten the prefix by removing the last character until it matches.
-
Return prefix:
- After all strings have been checked, the remaining prefix is the longest common prefix.
🔑 Complexity analysis
- > Time complexity:
O(S)
WhereS
is the sum of all characters in the array.- In the worst case, every character in the array will be compared.
- > Space complexity:
O(1)
because no additional data structures are used.
📋 Run on empty
enter: strs = ["flower", "flow", "flight"]
Alternative Solution: Vertical Scan
Instead of comparing strings individually, you can compare characters at every index in all strings.
var longestCommonPrefix = function(strs) {
if (!strs.length) return "";
for (let i = 0; i < strs[0].length; i++) {
const char = strs[0][i];
for (let j = 1; j < strs.length; j++) {
if (i >= strs[j].length || strs[j][i] !== char) {
return strs[0].slice(0, i);
}
}
}
return strs[0];
};
🔑 Complexity analysis (vertical scan)
- > Time complexity:
O(S)
the same as horizontal scan. - > Space complexity:
O(1)
.
✨ Professional tips for interviews
- Clarify constraints: Confirm whether the array can be empty or contain strings of different lengths.
- Discuss edge cases:
- empty string array (
[]
→""
). - Single string input (
["single"]
→"single"
). - Strings without common prefix (
["dog", "cat"]
→""
).
- empty string array (
- Explain your chosen method: Highlight the difference between horizontal and vertical scanning.
📚 Learn more
Check out the full explanation and code walkthrough on my Dev.to post:
👉 length of last word – JavaScript solution
What is your solution to this problem? Let’s discuss it! 🚀