Longest Common Prefix
Longest Common Prefix is LeetCode 14 (Easy). You are given an array of strings strs and must return the longest string that every element starts with. If the strings share no starting character at all, return the empty string "".
- The prefix has to be common to all strings, not just to most of them or to some pair.
- A string may be empty, in which case the answer is
"".
There are at most 200 strings of at most 200 characters each, so any sensible scan is fast. The real work is stopping at the right place without reading past the end of a short string.
- 1 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- strs[i] consists of only lowercase English letters if it is non-empty.
Intuition
Write the strings one under another, left-aligned. The longest common prefix is the run of columns, from the left, in which every row shows the same letter. It ends at the first column where two rows differ, or where some row has already run out.
So read the grid column by column (vertical scanning), not string by string. The answer is a prefix of every string, so any one of them can be the reference that the others are checked against; strs[0] is the simplest. Because the scan stops at the first bad column, it never reads more than one column past the answer.
Use a column scan whenever several sequences have to agree position by position from the start: common prefixes, shared directory paths, a common leading run of version numbers. If the same prefix queries repeat over a changing set of words, build a trie instead.
Approach
Before reading on, decide what your code does for ["ab", "a"]. Which check stops the scan, and what happens if you test the character before the length?
Two ways to solve it
Check one column at a time across all strings and stop at the first mismatch.
- Work: reads at most one column past the answer.
- Memory: nothing extra.
- Early exit: stops at once if the first letters differ.
The standard answer.
After sorting, the first and last strings are the furthest apart, so the prefix they share is shared by every string in between.
- Work: the sort compares whole strings.
- Memory: a sorted copy of the list.
- Code: one short loop after the sort.
Easy to remember, but slower than one scan.
The vertical scan stops as soon as the prefix ends and needs no sort, so the steps, code and live demo below follow it. The sorting trick is a popular alternative; its code comes after the demo.
Fix a reference string
Use first = strs[0]. Every common prefix is a prefix of first, so position i only needs to run over first's characters, and slicing first gives the answer.
Scan one column at a time
For i = 0, 1, ... with ch = first[i], look at every other string s:
i == len(s):shas ended, so the prefix cannot reach positioni. Returnfirst[:i].s[i] != ch: the strings disagree here. Returnfirst[:i].
The length test must come first; otherwise s[i] reads past the end of a shorter string.
Return the reference if nothing failed
If the loop finishes, every string matched all of first, which means first is the shortest string or tied for it. Return first.
Why the first mismatch is the answer
Column i is checked only after every column before it matched in all strings, so first[:i] is common to all of them. The column that fails shows one string that does not continue it, so no longer common prefix exists. Together these give exactly the longest one.
Code in Python, C++ and Java
i == len(s) first also keeps s[i] from going out of range. Every column to the left matched in all strings, so the answer is the first 3 characters: "pre".Sort, then compare the ends
Sorting puts strings with longer shared starts next to each other, so the first and last strings in sorted order share the shortest prefix of any pair. The loop compares just those two, character by character.
Common pitfalls
Comparing characters before checking the length
if s[i] != ch or i == len(s):
if i == len(s) or s[i] != ch:
When s is shorter than first, s[i] raises an IndexError in Python, throws in Java and is undefined behaviour in C++. Short-circuit evaluation only protects you if the length test is on the left.
Edge cases
If it is strs[0], the loop never runs and "" is returned; anywhere else, i == len(s) fires at i = 0.
There is nothing to compare against, so the inner loop is empty and the whole string is returned.
Complexity
strs[1:] copies n references per column, which does not change the bound).Longest Common Prefix FAQ
What does horizontal scanning do differently?
Horizontal scanning, used by many solutions, starts with prefix = strs[0] and, for each later string, chops characters off the end until the string starts with prefix. It is easy to write but can do a lot of wasted work when strs[0] is long and a later string disagrees early.
When is a trie worth it?
When the same word set is queried many times, or words are added over time. For a single call, building the trie reads every character and allocates nodes, so the column scan is simpler and at least as fast.
Is there a Python built-in for this?
Yes: os.path.commonprefix(strs) compares the strings character by character and returns the longest common prefix. Despite its name it ignores path separators, so it works on any strings. In an interview, write the loop yourself and mention the built-in.