LeetCode #14 Easy

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.

Constraints
  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters if it is non-empty.
stringscan
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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?

1

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.

2

Scan one column at a time

For i = 0, 1, ... with ch = first[i], look at every other string s:

  • i == len(s): s has ended, so the prefix cannot reach position i. Return first[:i].
  • s[i] != ch: the strings disagree here. Return first[:i].

The length test must come first; otherwise s[i] reads past the end of a shorter string.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def longestCommonPrefix(self, strs: List[str]) -> str:
▶3 first = strs[0]
▶4 for i, ch in enumerate(first):
▶5 for s in strs[1:]:
▶6 if i == len(s) or s[i] != ch:
▶7 return first[:i]
▶8 return first
strs0123450flower1flow2flightprefixemptyrow 0 is the reference
first"flower"prefix can be no longer
strings3
Idea. The common prefix is a prefix of every string, so in particular of strs[0]. Walk its characters one position at a time and ask every other string whether it has the same character there. The first position where anyone disagrees (or runs out) ends the prefix.
strs0123450flower1flow2flightprefixemptyrow 1 has 'f' too
i0
ch'f'from strs[0]
strs[1][0]'f'match
Column 0: the reference character is f. "flow" is long enough and has f there, a match. One match is not enough; every string must agree.
strs0123450flower1flow2flightprefixemptyrow 2 has 'f' too
i0
ch'f'from strs[0]
strs[2][0]'f'match
"flight" also has f at position 0. That is every string.
strs0123450flower1flow2flightprefixfcolumn 0 agrees → prefix "f"
prefix"f"
next i1
All 3 strings have f at position 0, so it joins the prefix. Move to the next column; the prefix can only stop growing, never shrink, because earlier columns are settled.
strs0123450flower1flow2flightprefixfrow 1 has 'l' too
i1
ch'l'from strs[0]
strs[1][1]'l'match
Column 1: the reference character is l. "flow" is long enough and has l there, a match. One match is not enough; every string must agree.
strs0123450flower1flow2flightprefixfrow 2 has 'l' too
i1
ch'l'from strs[0]
strs[2][1]'l'match
"flight" also has l at position 1. That is every string.
strs0123450flower1flow2flightprefixflcolumn 1 agrees → prefix "fl"
prefix"fl"
next i2
All 3 strings have l at position 1, so it joins the prefix. Move to the next column; the prefix can only stop growing, never shrink, because earlier columns are settled.
strs0123450flower1flow2flightprefixflrow 1 has 'o' too
i2
ch'o'from strs[0]
strs[1][2]'o'match
Column 2: the reference character is o. "flow" is long enough and has o there, a match. One match is not enough; every string must agree.
strs0123450flower1flow2flightprefixfl'i' ≠ 'o' → return "fl"
i2
strs[2]'i'≠ 'o'
result"fl"
"flight" has i at position 2, but the reference has o. Every column to the left matched in all strings, so the answer is the first 2 characters: "fl".
05

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.

▶1class Solution:
▶2 def longestCommonPrefix(self, strs: List[str]) -> str:
▶3 words = sorted(strs)
▶4 first, last = words[0], words[-1]
▶5 i = 0
▶6 while i < len(first) and first[i] == last[i]:
▶7 i += 1
▶8 return first[:i]
06

Common pitfalls

Comparing characters before checking the length

✗ Wrong
if s[i] != ch or i == len(s):
✓ Right
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.

07

Edge cases

An empty string in the list

If it is strs[0], the loop never runs and "" is returned; anywhere else, i == len(s) fires at i = 0.

A single string

There is nothing to compare against, so the inner loop is empty and the whole string is returned.

08

Complexity

Time
O(n · m)
Space
O(1)
n strings, m = length of the answer. At most m + 1 columns are read, each across n strings, so in the worst case this is the total number of characters. No extra space beyond the returned slice (Python's strs[1:] copies n references per column, which does not change the bound).
09

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.