The problem, in one line. Given a list of words, return the longest start that every one of them shares, or an empty string if there is none. LeetCode 14.
The tell. “Start of the word” is the whole question, so shared beginnings are the topic, which is the home ground of a trie. This one is gentler than that: the answer can never be longer than the first word, so you can shrink a single candidate instead of building anything.
The wrong first idea
Put every word into a trie, then walk down from the root for as long as the current node has exactly one child and no word ends there.
It is correct, and it is the right picture of what the problem asks. It is also heavy. It builds one node per letter of every word, which is the whole input again in memory, to answer a question whose answer fits inside the first word.
The invariant
Start with the first word as the candidate. For each next word, keep only the letters the candidate shares with it from the front.
candidate flower
vs flow flow
vs flight fl
The sentence that stays true every step: the candidate is a start of every word seen so far. It can only get shorter, so when the last word has been compared, nothing longer could have survived.
The solution
def longest_common_prefix(strs):
prefix = strs[0]
for s in strs[1:]:
i = 0
while i < len(prefix) and i < len(s) and prefix[i] == s[i]:
i += 1 # grow the match letter by letter
prefix = prefix[:i] # keep only what this word also shares
return prefix
print(longest_common_prefix(["flower", "flow", "flight"]))
print(repr(longest_common_prefix(["dog", "racecar", "car"])))
print(longest_common_prefix(["solo"]))
fl
''
solo
func longestCommonPrefix(strs []string) string {
prefix := strs[0]
for _, s := range strs[1:] {
i := 0
for i < len(prefix) && i < len(s) && prefix[i] == s[i] {
i++ // grow the match letter by letter
}
prefix = prefix[:i] // keep only what this word also shares
}
return prefix
}
Same three calls print fl, "", solo (Go quotes an empty string where Python shows two single quotes).
Complexity
- Time O(S) where S is the total number of letters: each word is compared once, and never past the length of the candidate.
- Space O(1) beyond the answer, because the candidate is a slice of the first word.
Traps
- Scanning column by column with no length guard.
["ab", "a"]then reads past the end of the short word and crashes. - Counting shared letters instead of a shared start.
["abc", "cab"]share three letters in total, but the answer is the empty string. - Stopping after the second word.
["flower", "flow", "flight"]would answerflow, because only the third word cuts it down tofl.
Next in the ladder
Implement Trie (Prefix Tree) builds the structure this card talked itself out of, because once words are added one at a time and asked about later, sharing the start is worth storing.