Longest common prefix
Easy TimeO(n·m) SpaceO(1)
Given an array of strings words, return the longest run of characters that every one of them starts with, or the empty string "" when they share none. The run has to begin at the first character of each string, so the shortest string in the array bounds how long it can be. An empty array, or an empty string anywhere in it, makes the answer empty.
Examples
Example 1
- Input
- words = ["flower", "flow", "flight"]
- Output
- All three open with
"fl"fand thenl; at the third character"flight"hasiwhere the others haveo.
Example 2
- Input
- words = ["dog", "racecar", "car"]
- Output
- The three disagree on their very first character, so there is nothing to share.
""
The Code
function longestCommonPrefix(words) {
if (words.length === 0) return "";
let prefix = words[0];
for (let i = 1; i < words.length; i++) {
while (!words[i].startsWith(prefix)) {
prefix = prefix.slice(0, prefix.length - 1);
if (prefix === "") return "";
}
}
return prefix;
}
longestCommonPrefix(["flower", "flow", "flight"]);Done
More like this
All strings examples (13) →- Reverse words Split on whitespace, walk backwards, join again.
- Valid anagram Count letters up with one word, down with the other.
- Run-length encoding Collapse each run of repeats into a character and a count.
- First unique char Count every character first, then find the earliest with count 1.
- Longest unique substring A sliding window that jumps forward past any repeat.
- Caesar cipher Rotate each letter through the alphabet and wrap around.