Start learning free

LESSON 502 OF 673 · TRIES

Longest Common Prefix in Python: O(S) Time with a Trie

Practice O(S) Read the full explanation

You get a list of strings words. Return the longest prefix that all of them share.

A prefix is the start of a word. For example, "plan" is a prefix of "planet". Every word is also a prefix of itself.

If they share no letters at the start, return the empty string "".

 

Example 1:

Input: words = ["interview","internet","interval"]
Output: "inter"
Explanation: All three words start with "inter".
Their next letters are v, n and v.
These are not all the same, so the prefix ends there.

Example 2:

Input: words = ["sunset","sun","sunsets"]
Output: "sun"
Explanation: The word "sun" is the whole prefix.
The other two words start with it.
Nothing longer fits in "sun".

Example 3:

Input: words = ["moon","stars","mars"]
Output: ""
Explanation: "stars" starts with s.
The other two words start with m.
So not even the first letter is shared.

 

Constraints:

  • words has 1 to 10,000 words.
  • Each word has 0 to 200 letters.
  • Each letter is from a to z.

Note:

Your solution should run in O(S) time. S is the total number of letters in words.



Store the words in a trie: a tree with one node per prefix. Words that start the same way share the same path from the root. Mark each node where a word ends.

Walk down from the root. At a node with exactly one child, where no word ends, every word goes on with the same letter. Stop at any other node.

Building the trie visits each letter once, and the walk is at most one word long: O(S) time.
The trie has at most S + 1 nodes, so the extra space is O(S).
STEP 1 OF 14
    Ctrl + Enter to check

    PYTHON · TRIES

    Longest Common Prefix in Python, explained

    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

    1. Design the node. In TrieNode.__init__, self.children is an empty dict that maps a letter to the child node for that letter. A dict finds the child in one step.
    2. Add the end flag. self.isEnd starts as False and becomes True on the node where a word ends. Only this flag tells a middle-of-the-path node from the end of a word.
    3. Create the root. root = TrieNode() is the empty prefix, where every word starts.
    4. Insert each word. The outer loop takes each word in words, and node starts at root for each one.
    5. Follow the letters. For each character c of the word, create a child under c if c is not in node.children, then move node to that child. Whether the child was already there or just made, the next step is the same.
    6. Mark the end. After the inner loop, set node.isEnd = True. This line belongs to the outer loop.
    7. Prepare the walk. cur starts at root and length at 0, since nothing is shared yet.
    8. Walk while the path is forced. The loop condition is len(cur.children) == 1 and not cur.isEnd.
    9. 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 to length. Since no word ends at cur, words[0] has a letter at index length.
    10. Return the prefix. words[0][:length] takes the first length letters 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. Writing children = {} in the class body would make all nodes share one.
    • Slices don't fail. words[0][:length] never raises an error for a too-large length, and words[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 words are 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 isEnd test is for. Without it, the condition is only len(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 raises IndexError: string index out of range, because the first word runs out of letters.
    • Only checking the first letter. Words like "moon" and "mars" share m but 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.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free