Shortest Palindrome — LeetCode 214 Python Solution
HardStringString MatchingHash FunctionRolling Hash
- Problem
- #214
- Pattern
- Hash Map
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a string s. You can convert s to a palindrome by adding characters in front of it.
Example
- Input
- s = "aacecaaa"
- Output
- "aaacecaaa"
Python solution
Python
class Solution:
def shortestPalindrome(self, s: str) -> str:
base = 131
mod = 10**9 + 7
n = len(s)
prefix = suffix = 0
mul = 1
idx = 0
for i, c in enumerate(s):
prefix = (prefix * base + (ord(c) - ord('a') + 1)) % mod
suffix = (suffix + (ord(c) - ord('a') + 1) * mul) % mod
mul = (mul * base) % mod
if prefix == suffix:
idx = i + 1
return s if idx == n else s[idx:][::-1] + sComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 214. Shortest Palindrome is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 214. Shortest Palindrome?
- LeetCode 214. Shortest Palindrome is rated Hard on LeetCode.
- What is the time complexity of LeetCode 214. Shortest Palindrome?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 214. Shortest Palindrome?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 214. Shortest Palindrome cover?
- LeetCode 214. Shortest Palindrome is tagged String, String Matching, Hash Function and Rolling Hash on LeetCode.