oneby7

String Matching Pattern matching

579. Shortest Palindrome

Hard

You are given a string s. You may add letters to the front of s, and nowhere else. Return the shortest palindrome you can make this way.

A palindrome reads the same forwards and backwards, such as "noon" or "refer". The empty string is a palindrome too. Answers are shown in double quotes, so an empty answer is "".

Example 1

Input: s = "abacus"

Output: "sucabacus"

Explanation: The longest start of abacus that is already a palindrome is aba. The letters after it, cus, are added to the front in reverse order, as suc.

Example 2

Input: s = ""

Output: ""

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

Example 3

Input: s = "abcd"

Output: "dcbabcd"

Explanation: Only the first letter is a palindrome on its own, so the other three letters go to the front, reversed.

Check your understanding

Work out the answer for this input before you write any code.

s = "aabba"

Constraints

  • 0 ≤ s.length ≤ 105
  • s holds only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.