Make a string a palindrome by adding the fewest characters to its front

Quick Overview

Given a lowercase string of up to 50,000 characters, add characters only to its front to form the shortest possible palindrome. It tests reasoning about palindromic prefixes and linear-time string matching, plus careful handling of edge cases such as the empty string.

Make a string a palindrome by adding the fewest characters to its front

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

You are given a string `s`. You may add characters to the front of `s`, and nowhere else, to turn it into a palindrome. Return the shortest palindrome you can produce this way. If `s` is already a palindrome, return it unchanged. ### Function Signature ```python def shortest_palindrome(s: str) -> str: ``` ### Constraints - `0 <= len(s) <= 5 * 10^4` - `s` consists of lowercase English letters only. ### Examples ```text Input: s = "aacecaaa" Output: "aaacecaaa" ``` The longest prefix of `s` that is already a palindrome is `"aacecaa"`. Only the final `"a"` is left over, so adding one `"a"` in front gives `"aaacecaaa"`, which reads the same in both directions. ```text Input: s = "abcd" Output: "dcbabcd" ``` The longest palindromic prefix is just `"a"`. The remaining `"bcd"` has no mirror on the left, so its reverse `"dcb"` goes in front. ```text Input: s = "" Output: "" ``` The empty string is already a palindrome, so nothing is added.

Overview: Given a lowercase string of up to 50,000 characters, add characters only to its front to form the shortest possible palindrome. It tests reasoning about palindromic prefixes and linear-time string matching, plus careful handling of edge cases such as the empty string.

Nov 24, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

You are given a string s. You may add characters to the front of s, and nowhere else, to turn it into a palindrome. Return the shortest palindrome you can produce this way. If s is already a palindrome, return it unchanged.

Function Signature

def shortest_palindrome(s: str) -> str:

Constraints

  • 0 <= len(s) <= 5 * 10^4
  • s consists of lowercase English letters only.

Examples

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

The longest prefix of s that is already a palindrome is "aacecaa". Only the final "a" is left over, so adding one "a" in front gives "aaacecaaa", which reads the same in both directions.

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

The longest palindromic prefix is just "a". The remaining "bcd" has no mirror on the left, so its reverse "dcb" goes in front.

Input: s = ""
Output: ""

The empty string is already a palindrome, so nothing is added.