Shortest Palindrome

Asked atOracle
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given a string s convert it into a palindrome by adding characters to the beginning of it. Return the shortest palindrome you can create by performing this transformation.

Input: s = "aacecaaa" Output: aaacecaaa Explanation: Adding "a" to the front of "aacecaaa" makes it a palindrome: "aaacecaaa".

Input: s = "race" Output: ecarace Explanation: By adding "eca" in front of "race", the shortest palindrome "ecarace" is formed.

Input: s = "abcd"

  • 1 <= s.length <= 104

cpp

class Solution{
  public:		
	string shortestPalindrome(string s) {
	     
	}
};

java

class Solution {
    public String shortestPalindrome(String s) {
  
    }
}

python

class Solution:
    def shortestPalindrome(self, s: str) -> str:

javascript

class Solution {
    shortestPalindrome(s) {
      
    }
}

csharp

class Solution {
    public string ShortestPalindrome(string s) {

    }
}

go

func shortestPalindrome(s string) string {

}
Stuck? Show a way to structure it+
  1. 01Reverse the input.
  2. 02Concatenate original, a delimiter, and reversed.
  3. 03Compute its prefix function.
  4. 04Use the final value as longest palindromic prefix length.
  5. 05Prepend the unmatched reversed suffix.

Reference answer

Then expect these follow-ups

  • Can a rolling hash implement this with collision risk?

    Tests: implementation extension

  • How would you build the shortest palindrome by appending instead?

    Tests: follow-up reasoning

Hiring now

Software engineer roles are open right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior Software Engineer -.NET

    Tyler Technologies · Annapolis, Maryland

  • Software Development Engineer II

    SaaS Labs · Bengaluru, Karnataka, India

  • Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)

    Metropolitan Transportation Authority · New York, NY

Or practice this question first

Next question