LeetCode 14: Longest Common Prefix — Python Solution

LeetCode 14: Longest Common Prefix is an Easy array / string problem. This Python walkthrough develops a vertical character scan solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyEasy
TopicArray / String
Reusable patternvertical character scan
ComplexityO(total compared characters) time and O(1) extra space

Recognizing the pattern

Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.

For this problem specifically, compare characters column by column against the first string and stop at the first missing or different character. The invariant worth writing beside the code is: Every character before the current column matches in all strings.

Step-by-step algorithm

  1. Identify the input state consumed by longestCommonPrefix(strs) and initialize the data required by the vertical character scan pattern.
  2. Compare characters column by column against the first string and stop at the first missing or different character.
  3. After each update, verify the page’s central invariant: Every character before the current column matches in all strings.
  4. Finish only after the boundary behavior is covered: An empty list or an empty string yields an empty prefix.

Python solution

class Solution:
    def longestCommonPrefix(self, strs):
        if not strs:
            return ""
        for i, char in enumerate(strs[0]):
            if any(i == len(word) or word[i] != char for word in strs[1:]):
                return strs[0][:i]
        return strs[0]

Reading the implementation

The main entry point is longestCommonPrefix(strs). The implementation keeps little named state because each operation can be resolved directly from the current input position.

A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, compare characters column by column against the first string and stop at the first missing or different character.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Compare characters column by column against the first string and stop at the first missing or different character. Each update records the current item without invalidating earlier decisions; consequently, every character before the current column matches in all strings.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(total compared characters) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().longestCommonPrefix(["flower","flow","flight"]) == "fl"

Common mistakes and edge cases

  • Problem-specific boundary: An empty list or an empty string yields an empty prefix.
  • Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
  • Invariant check: after every update, confirm that every character before the current column matches in all strings.

Interview review checklist

  • Explain why vertical character scan matches the structure of this input.
  • State the invariant in one sentence before tracing code: Every character before the current column matches in all strings.
  • Derive O(total compared characters) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: An empty list or an empty string yields an empty prefix.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 58. Length of Last Word · Next: 151. Reverse Words in a String