Problem overview
The method longestCommonPrefix receives a list of strings, words, and returns the longest prefix that every word starts with. A prefix is the start of a word, and every word is a prefix of itself. If the words don't even share their first letter, the answer is the empty string "". A word may itself be empty, and all letters are from a to z.
For ["interview", "internet", "interval"] all three words start with "inter", and their next letters are v, n and v, so the answer is "inter". For ["sunset", "sun", "sunsets"] the answer is "sun": the word "sun" is the whole prefix, and nothing longer fits inside it. For ["moon", "stars", "mars"] the answer is "".
The statement asks for O(S) time, where S is the total number of letters in words. That is the cost of reading every letter once.
Approach: a trie of all the words
A trie is a tree with one node per prefix. The root stands for the empty prefix, and each edge is labelled with one letter. Words that start the same way share the same path from the root, so the part of the tree where there is only one choice is exactly the part all the words share.
That gives the plan: insert every word, then walk down from the root as long as the path is forced. At a node there are three situations:
- Exactly one child, and no word ends here. Every word continues with the same letter, so the prefix can grow by that letter.
- Two or more children. The words split here, so the prefix stops.
- A word ends here. That word has no more letters, so no longer prefix can be shared. In
["sunset", "sun", "sunsets"]the node for"sun"has one child, but the flag on it says a word ends there, and the walk must stop.
Comparing the words letter by letter without a trie works too, and so does sorting. The trie is the idea this chapter practises, and it keeps the cost proportional to the number of letters.
Step by step
- Design the node. In
TrieNode.__init__,self.childrenis an empty dict that maps a letter to the child node for that letter. A dict finds the child in one step. - Add the end flag.
self.isEndstarts asFalseand becomesTrueon the node where a word ends. Only this flag tells a middle-of-the-path node from the end of a word. - Create the root.
root = TrieNode()is the empty prefix, where every word starts. - Insert each word. The outer loop takes each
wordinwords, andnodestarts atrootfor each one. - Follow the letters. For each character
cof the word, create a child undercifcis not innode.children, then movenodeto that child. Whether the child was already there or just made, the next step is the same. - Mark the end. After the inner loop, set
node.isEnd = True. This line belongs to the outer loop. - Prepare the walk.
curstarts atrootandlengthat 0, since nothing is shared yet. - Walk while the path is forced. The loop condition is
len(cur.children) == 1 and not cur.isEnd. - Take one step. The only child is the next letter of every word, so it is also the next letter of the first word:
cur = cur.children[words[0][length]]. Then add 1 tolength. Since no word ends atcur,words[0]has a letter at indexlength. - Return the prefix.
words[0][:length]takes the firstlengthletters of the first word.
The solution in Python
class TrieNode:
def __init__(self):
self.children = {}
self.isEnd = False
class Solution:
def longestCommonPrefix(self, words: List[str]) -> str:
root = TrieNode()
for word in words:
node = root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.isEnd = True
cur = root
length = 0
while len(cur.children) == 1 and not cur.isEnd:
cur = cur.children[words[0][length]]
length += 1
return words[0][:length]
Python details worth noting:
- A fresh dict per node.
self.children = {}runs in__init__, so every node gets its own dict. Writingchildren = {}in the class body would make all nodes share one. - Slices don't fail.
words[0][:length]never raises an error for a too-largelength, andwords[0][:0]is the empty string. That is why the answer for["moon", "stars", "mars"]needs no special case. - Strings are immutable. The slice builds a new string, and the words in
wordsare left alone. - The type hint
List[str]only documents the parameter. Python doesn't check it at run time.
A run of the solution
['interview', 'internet', 'interval'] 'inter'
['sunset', 'sun', 'sunsets'] 'sun'
['moon', 'stars', 'mars'] ''
['solo'] 'solo'
['', 'abc'] ''
['abc', 'abc'] 'abc'
['abc', ''] ''
['ab', 'ab', 'ab'] 'ab'
Complexity
Time: O(S). Inserting a word costs one dict lookup and at most one node creation per letter, so building the trie costs O(S) in total. The walk takes at most as many steps as the length of the first word, which is already counted in S.
Space: O(S). In the worst case no two words share a letter, and the trie has one node per letter plus the root: at most S + 1 nodes. The returned slice adds at most one word's length on top.
Edge cases and common mistakes
- One word.
["solo"]returns"solo". The path has one child at every node until the end, where there are no children, and the loop stops. - An empty word.
["", "abc"]returns"". The root is marked as a word's end, so the walk stops at once. The order of the list doesn't matter, and["abc", ""]also returns"". - Duplicates.
["abc", "abc"]returns"abc". The second insertion follows the existing path and sets the same flag again. - A word that is a prefix of the others. This is the case the
isEndtest is for. Without it, the condition is onlylen(cur.children) == 1. With["sunset", "sun"]that version walks past"sun"and returns"sunset", which the second word doesn't start with. With["sun", "sunset"]it raisesIndexError: string index out of range, because the first word runs out of letters. - Only checking the first letter. Words like
"moon"and"mars"sharembut not the rest, so the walk must stop at the first node with two children. - Using the longest word. The answer can't be longer than the shortest word. The walk guarantees it, because it stops at that word's end node.
