Shortest Palindrome
Real-world version: Bead Strand MirrorThe statement here is our own: the same inputs, outputs and technique.
A strung necklace is described by strand, a string of lowercase letters naming the bead colours from the clasp end outwards. The far end of the strand is already knotted, so beads can be threaded on only at the clasp end -- that is, characters may be inserted before strand, and the letters of strand keep their order and stay at the back of the result.
A strand is mirrored when it reads the same colour sequence in either direction. Return the shortest mirrored strand that can be produced this way.
Examples
Example 1
- Input
- strand = "abab"
- Output
- "babab"
Threading one b at the clasp end gives "babab", which reads the same in either direction.
Example 2
- Input
- strand = "wxyz"
- Output
- "zyxwxyz"
Threading z, y and x at the clasp end gives "zyxwxyz", and the four original beads still sit at the back in their original order.
Example 3
- Input
- strand = "aabb"
- Output
- "bbaabb"
Threading b and b gives "bbaabb", which reads the same in either direction.
Example 4
- Input
- strand = "abcba"
- Output
- "abcba"
The strand already reads the same in either direction, so nothing is threaded on.
Constraints
- 0 <= strand.length <= 5 * 10^4
- strand consists of lowercase English letters only.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def shortest_palindrome(strand: str) -> str:public String shortestPalindrome(String strand)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 13 test cases: 13 passed
- Passed: 4 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Find Beautiful Indices in the Given Array IReal-world version: Nearby Marker PositionsMedium
- Longest Happy PrefixReal-world version: Longest Overlapping BorderHard
- Find the Index of the First Occurrence in a StringReal-world version: Locate the Routing TagEasy
- Repeated Substring PatternReal-world version: Ribbon Repeats a MotifEasy