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.
C++
#include <iostream>
#include <string>
using namespace std;
// function to check if a given string is a palindrome
bool isPalindrome(string s)
{
int n = s.length();
for (int i = 0; i < n / 2; i++) {
if (s[i] != s[n - i - 1]) {
return false;
}
}
return true;
}
// function to check if there exists at least one even-length palindromic substring
bool hasEvenLengthPalindrome(string s)
{
int n = s.length();
for (int i = 0; i < n; i++) {
for (int len = 2; i + len <= n; len += 2) {
if (isPalindrome(s.substr(i, len))) {
return true;
}
}
}
return false;
}
int main()
{
string s = "xzyyz";
if (hasEvenLengthPalindrome(s)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0;
}
Java
public class Main {
// function to check if a given string is a palindrome
public static boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < n / 2; i++) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
// function to check if there exists at least one even-length palindromic substring
public static boolean hasEvenLengthPalindrome(String s) {
int n = s.length();
for (int i = 0; i < n; i++) {
for (int len = 2; i + len <= n; len += 2) {
if (isPalindrome(s.substring(i, i + len))) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
String s = "xzyyz";
if (hasEvenLengthPalindrome(s)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
// This code is contributed by shivamgupta0987654321
Python
# Function to check if a given string is a palindrome
def isPalindrome(s):
n = len(s)
for i in range(n // 2):
if s[i] != s[n - i - 1]:
return False
return True
# Function to check if there exists at least one even-length palindromic substring
def hasEvenLengthPalindrome(s):
n = len(s)
for i in range(n):
for length in range(2, n - i + 1, 2):
if isPalindrome(s[i:i + length]):
return True
return False
if __name__ == "__main__":
s = "xzyyz"
if hasEvenLengthPalindrome(s):
print("YES")
else:
print("NO")
C#
using System;
public class GFG
{
// function to check if a given string is a palindrome
public static bool IsPalindrome(string s)
{
int n = s.Length;
for (int i = 0; i < n / 2; i++)
{
if (s[i] != s[n - i - 1])
{
return false;
}
}
return true;
}
// function to check if there exists at least one even-length palindromic substring
public static bool HasEvenLengthPalindrome(string s)
{
int n = s.Length;
for (int i = 0; i < n; i++)
{
for (int len = 2; i + len <= n; len += 2)
{
if (IsPalindrome(s.Substring(i, len)))
{
return true;
}
}
}
return false;
}
//Driver Code
public static void Main()
{
string s = "xzyyz";
if (HasEvenLengthPalindrome(s))
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
}
}
JavaScript
// function to check if a given string is a palindrome
function isPalindrome(s) {
const n = s.length;
for (let i = 0; i < Math.floor(n / 2); i++) {
if (s[i] !== s[n - i - 1]) {
return false;
}
}
return true;
}
// function to check if there exists at least one even-length palindromic substring
function hasEvenLengthPalindrome(s) {
const n = s.length;
for (let i = 0; i < n; i++) {
for (let len = 2; i + len <= n; len += 2) {
if (isPalindrome(s.substr(i, len))) {
return true;
}
}
}
return false;
}
// Driver code
const s = "xzyyz";
if (hasEvenLengthPalindrome(s)) {
console.log("YES");
} else {
console.log("NO");
}
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:
C++
// C++ program to check if there is a substring
// palindrome of even length.
#include <bits/stdc++.h>
using namespace std;
// function to check if two consecutive same
// characters are present
bool check(string s)
{
for (int i = 0; i < s.length() - 1; i++)
if (s[i] == s[i + 1])
return true;
return false;
}
int main()
{
string s = "xzyyz";
if (check(s))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
Java
// Java program to check if there is a substring
// palindrome of even length.
class GFG {
// function to check if two consecutive same
// characters are present
static boolean check(String s)
{
for (int i = 0; i < s.length() - 1; i++)
if (s.charAt(i) == s.charAt(i+1))
return true;
return false;
}
// Driver Code
public static void main(String[] args) {
String s = "xzyyz";
if (check(s))
System.out.println("YES");
else
System.out.println("NO");
}
}
Python3
# Python 3 program to check if there is
# a substring palindrome of even length.
# function to check if two consecutive
# same characters are present
def check(s):
for i in range (0, len(s)):
if (s[i] == s[i + 1]):
return True
return False
# Driver Code
s = "xzyyz"
if(check(s)):
print("YES")
else:
print("NO")
# This code is contributed
# by iAyushRAJ
C#
// C# program to check if there is a substring
// palindrome of even length.
using System;
public class GFG {
// function to check if two consecutive same
// characters are present
static bool check(String s)
{
for (int i = 0; i < s.Length - 1; i++)
if (s[i] == s[i+1])
return true;
return false;
}
// Driver Code
public static void Main() {
String s = "xzyyz";
if (check(s))
Console.WriteLine("YES");
else
Console.WriteLine("NO");
}
}
JavaScript
<script>
// Javascript program to check if there is
// a substring palindrome of even length.
// Function to check if two consecutive same
// characters are present
function check(s)
{
for(let i = 0; i < s.length - 1; i++)
if (s[i] == s[i + 1])
return true;
return false;
}
// Driver code
let s = "xzyyz";
if (check(s))
document.write("YES");
else
document.write("NO");
// This code is contributed by suresh07
</script>
PHP
<?php
// PHP program to check if there is a
// substring palindrome of even length.
// function to check if two consecutive
// same characters are present
function check($s)
{
for ($i = 0; $i < strlen($s) - 1; $i++)
if ($s[$i] == $s[$i + 1])
return true;
return false;
}
// Driver Code
$s = "xzyyz";
if (check($s))
echo "YES","\n";
else
echo "NO" ,"\n";
// This code is contributed by ajit
?>
Time complexity: O(N) where N is the length of the given string.
Auxiliary space: O(1), as constant extra space is used.
Similar Reads
Check if all the palindromic sub-strings are of odd length Given a string 's' check if all of its palindromic sub-strings are of odd length or not. If yes then print "YES" or "NO" otherwise. Examples: Input: str = "geeksforgeeks" Output: NO Since, "ee" is a palindromic sub-string of even length. Input: str = "madamimadam" Output: YES Brute Force Approach: S
10 min read
All distinct palindromic sub-strings of a given string Given a string str of lowercase ASCII characters. The task is to find all the distinct continuous palindromic sub-strings which are present in the string str. Examples: Input: str = "abaaa"Output: [ "a", "aa", "aaa", "aba", "b" ]Explanation: All 5 distinct continuous palindromic sub-strings are list
15+ min read
Check if K palindromic strings can be formed from a given string Given a string S of size N and an integer K, the task is to find whether the characters of the string can be arranged to make K palindromic strings simultaneously. Examples: Input: S = "annabelle", K = 2 Output: Yes Explanation: All characters of string S can be distributed into "elble" and "anna" w
7 min read
Check if a given string is a rotation of a palindrome Given a string, check if it is a rotation of a palindrome. For example your function should return true for "aab" as it is a rotation of "aba". Examples: Input: str = "aaaad" Output: 1 // "aaaad" is a rotation of a palindrome "aadaa" Input: str = "abcd" Output: 0 // "abcd" is not a rotation of any p
15+ min read
Check if concatenation of splitted substrings of two given strings forms a palindrome or not Given two strings a and b of the same length, the task is to check if splitting both the strings and concatenating their opposite substrings, i.e. concatenating the left substring of a with right substring of b or concatenating the left substring of b with right substring of a, forms a palindrome or
8 min read
Find all Palindrome Strings in given Array of strings Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array. Examples: Input: arr[] = {"abc", "car", "ada", "racecar", "cool"}Output: "ada", "ra
6 min read
Check if a linked list of strings forms a palindrome Given a linked list handling string data, check to see whether data is palindrome or not? For example, Input : a -> bc -> d -> dcb -> a -> NULL Output : True String "abcddcba" is palindrome. Output : a -> bc -> d -> ba -> NULL Output : False String "abcdba" is not palindro
6 min read
Count substrings of a given string whose anagram is a palindrome Given a string S of length N containing only lowercase alphabets, the task is to print the count of substrings of the given string whose anagram is palindromic. Examples: Input: S = "aaaa"Output: 10Explanation:Possible substrings are {"a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"}. Sinc
10 min read
Check if string can be rearranged so that every Odd length Substring is Palindrome Given a string S. The task is to check whether it is possible to rearrange the string such that every substring of odd length is a palindrome. Examples: Input: S = "oiooi" Output: YES The string can be rearranged as "oioio" Input: S = "yuyuo" Output: NO Approach: The very first observation is if all
7 min read
Find a palindromic string B such that given String A is a subsequence of B Given a string A . Find a string B , where B is a palindrome and A is a subsequence of B. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subs
6 min read