In this problem we have to find a minimum length palindrome from a given string. As length must be greater than one so we can not use a single character as a palindrome. We should consider only length 2 or 3. Why do we do that?  - Because if we think of a palindrome of even length then it must have a  palindrome of length 2 inside it. Example: “abaaba” is a palindrome of length 6 and inside it  “abaaba” bold letters also make a palindrome of length 2. We will always find a palindrome of length 2 in any even size palindrome and a palindrome of length 3 in any odd size (size>1) palindrome. E.g. “mymomym”.

At first we will search for a palindrome of length 2. If any two adjacent characters are the same then we can say that it’s a palindrome of length 2. If there exist multiple palindromes of length 2, we will consider the one which appears first in the string. That’s why we should iterate from the beginning of the string.

If there does not exist a 2 length palindrome then we will search for length 3. For length three palindrome characters of string[i] and string[i+2] must be the same. If none of them exist then we can declare that it’s impossible to find a palindrome from the given string.

Example:

“abcbdeddeg**” -** “dd” is  a palindrome of length 2 and “bcb” is palindrome of length 3.

“momofmom” - “mom” is a palindrome of length 3.

“abcba” - “bcb”  is  a palindrome of length 3.

“abba” - “bb” is  a palindrome of length 2.

“abcda”  - no palindrome (length>1) exists.

“abbacc” in this string there are three palindromes - “abba”, “bb” and “cc”. From this three palindrome strings “bb” and “cc”  have minimum length. But “bb”  has a minimum starting position, that's why “bb” is our answer.

Statistics

49% Solution Ratio
abu_fayeemEarliest, Mar '22
sodiumfis_hFastest, 0.0s
abu_fayeemLightest, 131 kB
mdnakib_025Shortest, 410B
Toph uses cookies. By continuing you agree to our Cookie Policy.