> ## 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.

# Shortest Palindrome Python Solution with Tests

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

LeetCode 214, [Hard](/catalog/hard). Topics: [String](/catalog/topics/string), Rolling Hash, [String Matching](/catalog/topics/string-matching), [Hash Function](/catalog/topics/hash-function), Manacher, Z Algorithm, Knuth-Morris-Pratt Algorithm. [View on LeetCode](https://leetcode.com/problems/shortest-palindrome/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 214   # by problem number
lcpy gen -s shortest_palindrome   # by problem name
```

## Problem

You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it.

Return the shortest palindrome you can find by performing this transformation.

### Examples

```
Input: s = "aacecaaa"
Output: "aaacecaaa"
```

```
Input: s = "abcd"
Output: "dcbabcd"
```

### Constraints

* 0 \<= s.length \<= 5 \* 10^4
* s consists of lowercase English letters only.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n)
    def shortest_palindrome(self, s: str) -> str:
        if not s:
            return s
        rev = s[::-1]
        combined = s + "#" + rev
        n = len(combined)
        pi = [0] * n
        for i in range(1, n):
            j = pi[i - 1]
            while j > 0 and combined[i] != combined[j]:
                j = pi[j - 1]
            if combined[i] == combined[j]:
                j += 1
            pi[i] = j
        longest = pi[-1]
        return rev[: len(s) - longest] + s
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.