KatInterview

Shortest Palindromic Superstring by Suffix–Prefix Overlap

StringsAuto-graded · 19 test cases
EasyAuto-gradedStringsstringspalindrometwo pointers

Last updated

Tests understanding of palindromic structure by finding the minimum characters to append to a string to make the whole string a palindrome.

Shortest Palindromic Completion

Given a non-empty string s, you want to turn it into a palindrome by appending the fewest possible characters to its right end.

Return the resulting palindrome string.

How it works

A palindrome reads the same forwards and backwards. You may only add characters to the right of s — you cannot remove or change existing characters, and you cannot add anything to the left.

Find the longest prefix of s that is itself a palindrome. Everything in s after that prefix must be "mirrored" and appended on the right to complete the palindrome.

More concretely:

  • Scan prefix lengths from the full string down to a single character.
  • The first (longest) prefix s[0:k] that is a palindrome tells you that the suffix s[k:] must be reversed and appended.
  • Append s[k:] reversed to the end of s and return that string.

If s itself is already a palindrome, return s unchanged (zero characters appended).

Constraints

  • 1 <= len(s) <= 2000
  • s consists of lowercase English letters only (a–z).
  • There is always a valid answer (in the worst case, append s[1:] reversed).
  • The answer is unique — there is exactly one shortest completion produced by the rule above.

Examples

Example 1

Input: shortest_palindromic_completion('racecar')

Output: 'racecar'

Example 2

Input: shortest_palindromic_completion('abcd')

Output: 'abcddcb'

Example 3

Input: shortest_palindromic_completion('aab')

Output: 'aabb'

Hints

Hint 1

Check whether the entire string is already a palindrome first — that is the best case with zero appended characters.

Hint 2

Use a helper that checks if a substring s[i:j] is a palindrome, then scan k from len(s) down to 1 to find the longest palindromic prefix.

Hint 3

Once you have the longest palindromic prefix s[0:k], the characters you need to append are the reverse of s[k:].