What is a Palindrome?

A palindrome is a word that reads the same forwards and backwards. In my universe, there are two kinds of palindrome: “Odd Pal” and “Even Pal”.

Even Pal

Even Pal is a palindrome which has an even length, for example: “ZYXXYZ”. In the visualization below you can see how we can split it into 2 parts that have size 3: “ZYX” and “XYZ” . This palindrome will always have two centres called Left Center” at index2 and “Right Center” at index3.

Even Pals

“Even Pal”

Notice that:

  • character at index2 = character at index3 (mirror 1)
  • character at index1 = character at index4 (mirror 2)
  • character at index0 = character at index5 (mirror 3)

It is because of the above equality of characters at their respective indexes that the string is a palindrome and the two parts look like a sequence of 3 mirrors.

Odd Pal

Odd Pal is a palindrome which has an odd length, example: “ZYXWXYZ”. In the visualization below you can see how we can split the string into 2 parts that have size 3: “ZYX” and “XYZ”, while “W” at index3 becomes the center.

Image for post

“Odd Pal”

Notice that:

  • character at index2 = character at index4 (mirror 1)
  • character at index1 = character at index5 (mirror 2)
  • character at index0 = character at index6 (mirror 3)

Notice how again the two parts look like a sequence of 3 mirrors.

Problem

The problem states that we have to find the longest substring that is a palindrome in the string. A substring is a section of a string that consists of contiguous elements. Some examples are:

Input1: “BABAD” | Output1: “BAB” or “ABA”

Input2: “CBBD” | Output2: “BB”

Input3: “A” | Output3: “A”

Solutions

O(n²) Complexity

The simplest way to solve for this is to take every index as 1) a center 2) a Left Center and expand outwards to make character comparisons and find mirrors. The sequence with the maximum number of mirrors would be returned. Seems very simple and intuitive but the complexity is O(n²) because expanding a palindrome around a center could take O(n) time and we will explore every index in the string to be a center and left center, so O(n²) would be the time complexity.

O(n) Complexity

We can improve this runtime if we think of a way where we can leverage the previous palindromes found (as we navigate through the string) and reduce the “expanding outwards” part. Luckily, this is possible with “Manachar’s algorithm”.

Manachar’s algorithm

Before diving into the algorithm itself, we need to learn a few things first. For simplicity we will be focusing on Odd Pals for the most part. So let’s learn a few things in order:

#palindrome #leetcode #algorithms #substring #coding #algorithms

LeetCode: Longest Palindromic Substring With Manachar’s Algorithm
1.90 GEEK