> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Longest Common Prefix Python Solution

> Tested Python solution for LeetCode 14 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 14, Easy. Topics: Array, String, Trie. [View on LeetCode](https://leetcode.com/problems/longest-common-prefix/description/).

Generate this problem as a practice environment: tested reference solution, 16 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 14   # by problem number
lcpy gen -s longest_common_prefix   # by problem name
```

## Problem

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string `""`.

### Examples

```
Input: strs = ["flower","flow","flight"]
Output: "fl"
```

```
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
```

### Constraints

* 1 \<= strs.length \<= 200
* 0 \<= strs\[i].length \<= 200
* `strs[i]` consists of only lowercase English letters if it is non-empty.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/longest_common_prefix/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/longest_common_prefix/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(S) where S is total characters across all strings
    # Space: O(1)
    def longest_common_prefix(self, strs: list[str]) -> str:
        if not strs:
            return ""

        # Vertical scan: compare each character index against all strings
        first = strs[0]
        for i, char in enumerate(first):
            for other in strs[1:]:
                # Stop when index exceeds a string's length or chars mismatch
                if i >= len(other) or other[i] != char:
                    return first[:i]

        return first
```

## Complexity

| Time                                                | Space |
| --------------------------------------------------- | ----- |
| O(S) where S is total characters across all strings | O(1)  |

## Tags

[Grind](/catalog/grind), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
