Tensorum
LeetCode 14 · Prefix / Misc

Longest Common Prefix

LeetCode 14 · Easy · solution, intuition & step-by-step walkthrough

Shrink a candidate prefix until every word starts with it.

EasyArrayStringTrie
0 msruntime · beats 100%
19.5 MBmemory · beats 12%
1approach
7accepted runs · last 2 Jun 2026

This is how I solved Longest Common Prefix (LeetCode 14), an easy problem from the Prefix / Misc pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Start with the first word as the candidate prefix. For each other word, chop characters off the end of the candidate until the word starts with it. Whatever survives every word is the answer.

Approach

  1. 1

    prefix = strs[0].

  2. 2

    For each word, while it doesn't start with prefix, drop the last character.

  3. 3

    Empty prefix → return ''.

How I solved it

Shrinking prefixPythonO(S) time
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        i=1
        prefix = strs[0]
        while i<len(strs):
            cur_word = strs[i]
            while not cur_word.startswith(prefix):
                prefix=prefix[:len(prefix)-1]
                if not prefix:
                    return ""
            i+=1
        return prefix
Loading the step-through…

Longest Common Prefix — FAQ

What is the intuition behind Longest Common Prefix?

Start with the first word as the candidate prefix. For each other word, chop characters off the end of the candidate until the word starts with it. Whatever survives every word is the answer.

How do you solve Longest Common Prefix (LeetCode 14)?

1. prefix = strs[0]. 2. For each word, while it doesn't start with prefix, drop the last character. 3. Empty prefix → return ''.

What is the time and space complexity of Longest Common Prefix?

Time: O(S) — total characters. Space: O(1). (Accepted approach: Shrinking prefix.)

What are common mistakes in Longest Common Prefix?

Return early when the prefix becomes empty.