Medium: Interview Core · Problem 29 of 82

Longest Common Prefix

MediumStringsPython

Write longest_common_prefix(words) that returns the longest string that every word in the list starts with. If there is none, return the empty string. An empty list also gives the empty string.

["flower", "flow", "flight"] gives "fl".

Understand the problem

Check the edge cases first.

What is the longest common prefix of ["dog", "racecar", "car"]? Type it, or type none if there is no common start.

The words start with d, r and c: no shared first letter. The answer is the empty string, which is what the function returns.

What is the longest common prefix of ["apple"], a list with a single word?

With one word, the whole word is a prefix shared by "all" the words.

What should longest_common_prefix(["", "abc"]) return?

  1. "abc"
  2. ""

The empty word has no characters, so the shared start can have no characters either.

Write the solution

Return the prefix as a string.

def longest_common_prefix(words):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

The answer can never be longer than which word? How could you shrink a candidate until all the words agree with it?

Hint 2: the shape of the answer

Start with the first word as the candidate. For each other word, cut letters off the end of the candidate until the word starts with it (word.startswith(candidate)). Check for an empty list first.

Reflect

Solution: shrink the prefix

def longest_common_prefix(words):
    if not words:
        return ""
    prefix = words[0]
    for word in words[1:]:
        while not word.startswith(prefix):
            prefix = prefix[:-1]
    return prefix

Another way: compare letter by letter with zip

def longest_common_prefix(words):
    if not words:
        return ""
    prefix = []
    for letters in zip(*words):
        if len(set(letters)) != 1:
            break
        prefix.append(letters[0])
    return "".join(prefix)

Another way: the standard library

import os.path

def longest_common_prefix(words):
    return os.path.commonprefix(words)

What this tests: startswith, slicing, zip(*words) (which stops at the shortest word) and edge cases.

Edge cases first: an empty list, one word, an empty word, all words equal. Say them aloud in an interview before coding; it shows you are reading the problem.

The zip idea: zip(*words) yields the first letters of all words, then the second letters, and so on, and stops when the shortest word runs out. A column where the letters are not all equal ends the prefix.

Cost: O(total number of characters) in the worst case.

What an interviewer might ask next: What if the list has a million words? Could you stop early? (Yes: the answer can be no longer than the shortest word, and the prefix can only shrink.)