Longest Common Prefix (LeetCode 14): Solution and Explanation

Easy
String
Trie

Given a list of strings, return the longest string that every one of them starts with. If the strings share no common starting characters, return an empty string.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The answer can never be longer than any single string, and it must be a prefix of the first string in particular. That gives a natural starting point: assume the whole first string is the common prefix, then let every other string cut it down to size.

For each following string, check whether it starts with the current prefix. If it does, the prefix survives unchanged. If it does not, drop the last character of the prefix and try again, repeating until it fits or becomes empty. Each string can only shrink the prefix, never grow it, so once it is empty you can stop early, because nothing can bring characters back.

This is often called horizontal scanning, because you compare the prefix with one string at a time across the list. An alternative mental model is vertical scanning, where you compare the first character of every string, then the second, and so on, stopping at the first mismatch. Both arrive at the same answer; the shrinking approach is especially compact in Python thanks to startswith. For a list of a few hundred short strings, the difference between the two styles is negligible, so pick the one you can write without bugs.

Approach: Horizontal scanning with a shrinking prefix

  1. If the list is empty, return an empty string.
  2. Set prefix to the first string.
  3. For each remaining string s, loop while s does not start with prefix.
  4. Inside that loop, remove the last character of prefix. If it becomes empty, return an empty string immediately.
  5. After every string has been processed, return prefix.

Step-by-step example

strs = ["flower","flow","flight"]
  1. The prefix starts as 'flower'.
  2. 'flow' does not start with 'flower', so the prefix shrinks to 'flowe', which still fails, and then to 'flow', which fits.
  3. 'flight' does not start with 'flow' or 'flo', so the prefix shrinks twice more to 'fl', which fits.
  4. No strings remain, so the function returns 'fl'.

Code: Python, Java, C++

1class Solution:
2    def longestCommonPrefix(self, strs: List[str]) -> str:
3        if not strs:
4            return ""
5
6        prefix = strs[0]
7        for s in strs[1:]:
8            while not s.startswith(prefix):
9                prefix = prefix[:-1]
10                if not prefix:
11                    return ""
12        return prefix

Time and space complexity

Time

O(n × m + m²)

With n strings and m the length of the first one, each string has one successful startswith check costing at most O(m). Since the prefix only shrinks, there are at most m failed checks in total across the whole run, each costing O(m). Given the small limits here this is very fast.

Space

O(m)

Python slicing creates a new prefix string on every shrink, but only one prefix of at most m characters is alive at a time.

Other approaches

Vertical scanning (time O(S), space O(1))

Walk character positions from 0 upward and compare that character across all strings, stopping at the first mismatch or the end of the shortest string. It touches each character at most once, which makes it O(S) where S is the total length.

Sort then compare extremes (time O(S log n), space O(m))

Sort the strings and compare only the first and last in sorted order, since any prefix they share is shared by everything between them. It is elegant but pays for the sort.

Common mistakes

  • Starting the prefix as an empty string and trying to grow it. The shrinking approach needs a maximal starting candidate, and the first string is the natural one.
  • Forgetting that a string in the list may itself be empty. The prefix then shrinks to nothing, and the early return handles it correctly.
  • In vertical scanning, indexing past the end of a shorter string. Always stop at the length of the shortest string.
  • Using in instead of startswith. 'low' is in 'flower', but it is not a prefix of it.

Frequently asked questions

What is the time complexity of Longest Common Prefix?

For the shrinking method it is O(n × m + m²), where m is the length of the first string, because each string gets one successful prefix check and the prefix can only shrink m times. The vertical scan is O(S), the total number of characters.

Is a trie useful for Longest Common Prefix?

For a single query a trie is overkill, since building it costs O(S) and you can get the answer with a direct scan. A trie pays off when you need the common prefix of many changing sets of strings or prefix queries against the same set.

What if the list contains only one string?

Then the whole string is the answer, because it trivially starts with itself. The loop over the remaining strings simply does not run, so no special case is needed. An empty input list is handled separately by the first check, which returns an empty string.

Does the order of strings matter?

Not for the result. It can affect speed, since starting from the shortest string gives a smaller initial prefix to shrink.