VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-string-contains-a-palindromic-sub-string-of-even-length/

⇱ Check if a string contains a palindromic sub-string of even length - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a string contains a palindromic sub-string of even length

Last Updated : 16 Oct, 2023

S is string containing only lowercase English alphabets. We need to find if there exists at least one palindromic sub-string whose length is even. 

Examples:

Input : aassss
Output : YES
Input : gfg
Output : NO

Approach:

Approach to solve this problem is to check all even-length substrings of the given string and check if any of them is a palindrome. This can be done using nested loops. The outer loop will iterate over all possible starting indices of even-length substrings, while the inner loop will iterate over all possible lengths of such substrings. At each iteration, we can check if the current substring is a palindrome.

  • Define a function named "isPalindrome" that takes a string as input and returns a boolean indicating whether the given string is a palindrome or not.
  • Define another function named "hasEvenLengthPalindrome" that takes a string as input and returns a boolean indicating whether there exists at least one even-length palindromic substring in the given string or not.
  • Traverse the string from the start and fix a starting position "i".
  • Traverse the string from the fixed starting position and fix a length of the substring "len" such that len is even and (i+len) <= n.
  • Check if the substring starting from position i and of length len is a palindrome or not by calling the isPalindrome function. If yes, return true.
  • If the loop completes successfully, return false.

Output
YES

Time Complexity: O(N^3), where N is the length of the string s. This is because we are using nested loops to generate all possible substrings of even length and then checking if each substring is a palindrome. The isPalindrome function has a time complexity of O(N/2) = O(N) as we are iterating over half of the string.

Space Complexity: O(1) as we are not using any extra data structure to store the substrings.

Notice that a palindrome of even length must contain two same alphabets in the middle. So we just need to check for this condition. If we find two consecutive same alphabets in the string then we output "YES" otherwise "NO".

Below is the implementation: 


Output
YES

Time complexity: O(N) where N is the length of the given string.
Auxiliary space: O(1), as constant extra space is used.

Comment