All problems
0382HardStringRolling HashString MatchingHash FunctionManacherZ AlgorithmKnuth–Morris–Pratt Algorithm

Bead Strand Mirror

Tracked in this browser only
Write code

Trains the technique from

LeetCode 214Shortest Palindrome

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def shortest_palindrome(strand: str) -> str:
Java
public String shortestPalindrome(String strand)
September 7
Apply