214. Shortest Palindrome LeetCode Solution

In this guide, you will get 214. Shortest Palindrome LeetCode Solution with the best time and space complexity. The solution to Shortest Palindrome problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Shortest Palindrome solution in C++
  4. Shortest Palindrome solution in Java
  5. Shortest Palindrome solution in Python
  6. Additional Resources
214. Shortest Palindrome LeetCode Solution image

Problem Statement of Shortest Palindrome

You are given a string s. You can convert s to a palindrome by adding characters in front of it.
Return the shortest palindrome you can find by performing this transformation.

Example 1:
Input: s = “aacecaaa”
Output: “aaacecaaa”
Example 2:
Input: s = “abcd”
Output: “dcbabcd”

Constraints:

0 <= s.length <= 5 * 104
s consists of lowercase English letters only.

Complexity Analysis

  • Time Complexity: O(n^2)
  • Space Complexity: O(n)

214. Shortest Palindrome LeetCode Solution in C++

class Solution {
 public:
  string shortestPalindrome(string s) {
    const string t = {s.rbegin(), s.rend()};
    const string_view sv_s(s);
    const string_view sv_t(t);

    for (int i = 0; i < s.length(); ++i)
      if (sv_s.substr(0, s.length() - i) == sv_t.substr(i))
        return t.substr(0, i) + s;

    return t + s;
  }
};
/* code provided by PROGIEZ */

214. Shortest Palindrome LeetCode Solution in Java

class Solution {
  public String shortestPalindrome(String s) {
    final String t = new StringBuilder(s).reverse().toString();

    for (int i = 0; i < t.length(); ++i)
      if (s.startsWith(t.substring(i)))
        return t.substring(0, i) + s;

    return t + s;
  }
}
// code provided by PROGIEZ

214. Shortest Palindrome LeetCode Solution in Python

class Solution:
  def shortestPalindrome(self, s: str) -> str:
    t = s[::-1]

    for i in range(len(t)):
      if s.startswith(t[i:]):
        return t[:i] + s

    return t + s
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.