Top Interview 150
The Longest Common Prefix problem is a classic string manipulation challenge that tests your ability to identify shared patterns among strings. Let’s break down
Output: "fl"
Alternative Solution: Vertical Scanning
Instead of comparing strings one by one, you can compare characters at each index across 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 Scanning)
- > Time Complexity:
O(S), same as horizontal scanning. - > Space Complexity:
O(1).
✨ Pro Tips for Interviews
- Clarify constraints: Confirm whether the array can be empty or contain strings of varying lengths.
- Discuss edge cases:
- Empty string array (
[]→""). - Single string input (
["single"]→"single"). - Strings with no common prefix (
["dog", "cat"]→"").
- Empty string array (
- Explain your choice of approach: 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’s your approach to solving this problem? Let’s discuss! 🚀
SOCIAL SHARE CARD GENERATOR