← Back to Algorithms, page 1

algorithms-0014 · Easy fresher

Longest common prefix: find the longest prefix shared by every string in a list.

Compare characters column by column: take position i of the first word and check it against position i of every other word, stopping at the first mismatch or the end of any word. This costs at most the total number of characters, O(S). A neat alternative compares only the lexicographically smallest and largest strings, since any prefix they share is shared by everything between them.

Full answer

Problem

Given a list of strings, return the longest string that is a prefix of all of them, or "" if none.

Example: ["flower", "flow", "flight"] gives "fl"; ["dog", "racecar", "car"] gives "".

Constraints: 0 <= len(words) <= 200, each word up to 200 lowercase letters.

Brute force

Take each prefix of the first word, longest first, and check whether every word starts with it: O(m^2 x n) for word length m and n words.

Optimal approach: vertical scan

For each index i of the first word, check that every other word has a character at i and that it matches. Return first[:i] at the first failure; if none, the whole first word is the answer.

Alternative: compare min and max

Lexicographic order puts words with a common prefix together. The smallest and largest words differ earliest; any prefix they share is shared by every word in between. So compute min(words) and max(words) and their common prefix. This is O(S) for the min and max plus O(m) for the comparison, with simple code.

Why it works

A common prefix must match at every position for every word, so the first column with a mismatch (or a word that ends) is exactly where the prefix stops. The scan never looks past that column, so it does at most n characters of work per prefix character.

Complexity

Vertical scan: O(S) time where S is the total number of characters, O(1) extra space. Min/max: O(S) time, O(1) extra space.

Code

python
def longest_common_prefix(words):
    """Vertical scan: compare column by column. O(total characters) time, O(1) extra."""
    if not words:
        return ""
    first = words[0]
    for i, ch in enumerate(first):
        for w in words[1:]:
            if i == len(w) or w[i] != ch:
                return first[:i]
    return first


def longest_common_prefix_minmax(words):
    """Only the lexicographically smallest and largest words need comparing."""
    if not words:
        return ""
    a, b = min(words), max(words)
    i = 0
    while i < len(a) and i < len(b) and a[i] == b[i]:
        i += 1
    return a[:i]


if __name__ == "__main__":
    for f in (longest_common_prefix, longest_common_prefix_minmax):
        assert f(["flower", "flow", "flight"]) == "fl"
        assert f(["dog", "racecar", "car"]) == ""
        assert f([]) == ""
        assert f(["alone"]) == "alone"
        assert f(["ab", "a"]) == "a"
        assert f(["", "abc"]) == ""
        assert f(["same", "same"]) == "same"
    print("all tests passed")

Save as a14_longest_common_prefix.py and run python3 a14_longest_common_prefix.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty list (return ""). One word (the word itself). An empty string in the list (answer ""). A word that is a prefix of the others (["ab", "a"] gives "a"). All identical words.

Pattern

Vertical scanning across several sequences. For many queries over a fixed set, a trie gives the prefix by following nodes with a single child; the trie is covered in a later batch.

python
def longest_common_prefix(words):
    """Vertical scan: compare column by column. O(total characters) time, O(1) extra."""
    if not words:
        return ""
    first = words[0]
    for i, ch in enumerate(first):
        for w in words[1:]:
            if i == len(w) or w[i] != ch:
                return first[:i]
    return first


def longest_common_prefix_minmax(words):
    """Only the lexicographically smallest and largest words need comparing."""
    if not words:
        return ""
    a, b = min(words), max(words)
    i = 0
    while i < len(a) and i < len(b) and a[i] == b[i]:
        i += 1
    return a[:i]


if __name__ == "__main__":
    for f in (longest_common_prefix, longest_common_prefix_minmax):
        assert f(["flower", "flow", "flight"]) == "fl"
        assert f(["dog", "racecar", "car"]) == ""
        assert f([]) == ""
        assert f(["alone"]) == "alone"
        assert f(["ab", "a"]) == "a"
        assert f(["", "abc"]) == ""
        assert f(["same", "same"]) == "same"
    print("all tests passed")

Vertical scan and the min/max comparison, both checked on the same tests.

Complexity

Time: O(S), where S is the total number of characters. Space: O(1) extra. The vertical scan stops early at the first mismatch, so it often reads far fewer than S characters.

By level

Fresher: Writes the column-by-column scan with correct bounds checks and tests the classic examples. Should handle an empty list of words.

Mid: Explains the min/max argument, compares with binary search on the prefix length and states O(S). Compares vertical scanning with sorting and comparing the first and last words.

Senior: Discusses tries for repeated queries, divide and conquer, and memory trade-offs for very large word sets. Mentions a trie when many prefix queries are needed.

Key points

  • Scan column by column across all words
  • Stop at the first mismatch or the end of any word
  • Min and max words bound the common prefix
  • Total work is O(S)
  • Empty list and empty strings return ""

Common mistakes

  • Indexing past the end of a shorter word
  • Sorting the whole list when min and max suffice
  • Forgetting the empty list case
  • Returning the shortest word without checking it

Follow-ups

  • How would you answer many prefix queries quickly?
  • What is the binary search on prefix length approach?
  • How would you find the longest common suffix?

Tips

  • Start with the column scan; it is the clearest
  • Mention the min/max trick as a bonus
  • Test a word that is a prefix of others

Evaluation rubric

  • Correct algorithm with boundary checks
  • Handles empty and single-word lists
  • Correct complexity
  • Mentions an alternative