Check if all the palindromic sub-strings are of odd length - GeeksforGeeks

14 Jul, 2021
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:
Simply, iterate over each sub-string of ‘s’ and check if it is a palindrome. If it is a palindrome then it must of odd length.Below is the implementation of the above approach:
C++
Java
Python
C#
PHP
Javascript
// C++ implementation of the approach#include<bits//stdc++.h>using namespace std; // Function to check if// the string is palindromebool checkPalindrome(string s){    for (int i = 0; i < s.length(); i++)    {        if(s[i] != s[s.length() - i - 1])            return false;    }    return true;} // Function that checks whether// all the palindromic// sub-strings are of odd length.bool CheckOdd(string s){int n = s.length();for (int i = 0; i < n; i++){         // Creating each substring    string x = "";    for (int j = i; j < n; j++)    {        x += s[j];                 // If the sub-string is        // of even length and        // is a palindrome then,        // we return False        if(x.length() % 2 == 0 &&        checkPalindrome(x) == true)            return false;        }    }         return true;} // Driver codeint main(){    string s = "geeksforgeeks";    if(CheckOdd(s))        cout<<("YES");    else        cout<<("NO");}// This code is contributed by// Sahil_shelangia
// Java implementation of the approachimport java.util.*;class GFG{ // Function to check if// the string is palindromestatic boolean checkPalindrome(String s){    for (int i = 0; i < s.length(); i++)    {        if(s.charAt(i) != s.charAt(s.length() - i - 1))            return false;    }    return true;} // Function that checks whether// all the palindromic// sub-strings are of odd length.static boolean CheckOdd(String s){int n = s.length();for (int i = 0; i < n; i++){         // Creating each substring    String x = "";    for (int j = i; j < n; j++)    {        x += s.charAt(j);                 // If the sub-string is        // of even length and        // is a palindrome then,        // we return False        if(x.length() % 2 == 0 &&        checkPalindrome(x) == true)            return false;        }    }         return true;} // Driver codepublic static void main(String args[]){    String s = "geeksforgeeks";    if(CheckOdd(s))        System.out.print("YES");    else        System.out.print("NO");}} // This code is contributed// by Arnab Kundu
# Python implementation of the approach # Function to check if# the string is palindrome  def checkPalindrome(s):    for i in range(len(s)):        if(s[i] != s[len(s)-i-1]):            return False    return True # Function that checks whether# all the palindromic# sub-strings are of odd length.  def CheckOdd(s):    n = len(s)    for i in range(n):         # Creating each substring        x = ""        for j in range(i, n):            x += s[j]            # If the sub-string is            # of even length and            # is a palindrome then,            # we return False            if(len(x) % 2 == 0                    and checkPalindrome(x) == True):                return False    return True  # Driver codes = "geeksforgeeks"if(CheckOdd(s)):    print("YES")else:    print("NO")
// C# implementation of the approachusing System;                      public class GFG { // Function to check if// the string is palindromestatic bool checkPalindrome(String s){    for (int i = 0; i < s.Length; i++)    {        if(s[i] != s[(s.Length - i - 1)])            return false;    }    return true;} // Function that checks whether// all the palindromic// sub-strings are of odd length.static bool CheckOdd(String s){int n = s.Length;for (int i = 0; i < n; i++){         // Creating each substring    String x = "";    for (int j = i; j < n; j++)    {        x += s[j];                 // If the sub-string is        // of even length and        // is a palindrome then,        // we return False        if(x.Length % 2 == 0 &&        checkPalindrome(x) == true)            return false;        }    }         return true;} // Driver codepublic static void Main(){    String s = "geeksforgeeks";    if(CheckOdd(s))        Console.Write("YES");    else        Console.Write("NO");}} /* This code is contributed by 29AjayKumar*/
<?php// PHP implementation of the approach // Function to check if the string// is palindromefunction checkPalindrome($s){    for ($i = 0; $i < strlen($s); $i++)    {        if($s[$i] != $s[strlen($s) - $i - 1])            return false;    }    return true;} // Function that checks whether all the// palindromic sub-strings are of odd length.function CheckOdd($s){    $n = strlen($s);    for ($i = 0; $i < $n; $i++)    {                 // Creating each substring        $x = "";        for ($j = $i; $j < $n; $j++)        {            $x = $x.$s[$i];                         // If the sub-string is            // of even length and            // is a palindrome then,            // we return False            if(strlen($x) % 2 == 0 &&            checkPalindrome($x) == true)                return false;        }    }             return true;} // Driver code$s = "geeksforgeeks";if(CheckOdd($s))    echo "YES";else    echo "NO";     // This code is contributed by ita_c?>
<script> // JavaScript implementation of the approach // Function to check if// the string is palindromefunction checkPalindrome(s){    for (let i = 0; i < s.length; i++)    {        if(s[i] != s[s.length - i - 1])            return false;    }    return true;} // Function that checks whether// all the palindromic// sub-strings are of odd length.function CheckOdd(s){    let n = s.length;for (let i = 0; i < n; i++){          // Creating each substring    let x = "";    for (let j = i; j < n; j++)    {        x += s[j];                  // If the sub-string is        // of even length and        // is a palindrome then,        // we return False        if(x.length % 2 == 0 &&        checkPalindrome(x) == true)            return false;        }    }          return true;} // Driver codelet s = "geeksforgeeks";if(CheckOdd(s))    document.write("YES");else    document.write("NO");  // This code is contributed by avanitrachhadiya2155 </script>
NO
Efficient Approach: To check if all palindromic substrings of s have odd lengths, we can search for an even length palindromic substring of it. We know that every even length palindrome has at least two consecutive characters that are identical (e.g. cxxa, ee). Therefore, we can check two consecutive characters at a time to see if they are the same. If so, then s has an even length palindromic substring and hence output will be NO, and if we find no even length substring the answer will be YES.
We can complete this checking after one string traversal.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include<bits//stdc++.h>using namespace std; // Function that checks whether s// contains a even length palindromic// sub-strings or not.bool CheckEven(string s){  for (int i = 1; i < s.size(); ++i) {        if (s[i] == s[i - 1]) {            return true;        }    }    return false;} // Driver codeint main(){    string s = "geeksforgeeks";    if(CheckEven(s)==false)        cout<<("YES");    else        cout<<("NO");}// This code is contributed by// Aditya Jaiswal
// Java implementation of the approachimport java.util.*;class GFG{ // Function to check if// the string is palindromestatic boolean checkPalindrome(String s){    for (int i = 0; i < s.length(); i++)    {        if(s.charAt(i) != s.charAt(s.length() - i - 1))            return false;    }    return true;} // Function that checks whether// all the palindromic// sub-strings are of odd length.static boolean CheckOdd(String s){int n = s.length();for (int i = 0; i < n; i++){         // Creating each substring    String x = "";    for (int j = i; j < n; j++)    {        x += s.charAt(j);                 // If the sub-string is        // of even length and        // is a palindrome then,        // we return False        if(x.length() % 2 == 0 &&           checkPalindrome(x) == true)            return false;        }    }         return true;} // Driver codepublic static void main(String args[]){    String s = "geeksforgeeks";    if(CheckOdd(s))        System.out.print("YES");    else        System.out.print("NO");}} // This code is contributed// by Arnab Kundu
# Python implementation of the approach # Function to check if# the string is palindromedef checkPalindrome(s):    for i in range(len(s)):        if(s[i] != s[len(s)-i-1]):            return False    return True # Function that checks whether# all the palindromic# sub-strings are of odd length.def CheckOdd(s):    n = len(s)    for i in range(n):         # Creating each substring        x = ""        for j in range(i, n):            x += s[j]            # If the sub-string is            # of even length and            # is a palindrome then,            # we return False            if(len(x)% 2 == 0                  and checkPalindrome(x) == True):                return False    return True # Driver codes = "geeksforgeeks"if(CheckOdd(s)):    print("YES")else:    print("NO")
// C# implementation of the approachusing System;                      public class GFG { // Function to check if// the string is palindromestatic bool checkPalindrome(String s){    for (int i = 0; i < s.Length; i++)    {        if(s[i] != s[(s.Length - i - 1)])            return false;    }    return true;}  // Function that checks whether// all the palindromic// sub-strings are of odd length.static bool CheckOdd(String s){int n = s.Length;for (int i = 0; i < n; i++){          // Creating each substring    String x = "";    for (int j = i; j < n; j++)    {        x += s[j];                  // If the sub-string is        // of even length and        // is a palindrome then,        // we return False        if(x.Length % 2 == 0 &&           checkPalindrome(x) == true)            return false;        }    }          return true;}  // Driver codepublic static void Main(){    String s = "geeksforgeeks";    if(CheckOdd(s))        Console.Write("YES");    else        Console.Write("NO");}}  /* This code is contributed by 29AjayKumar*/
<?php// PHP implementation of the approach // Function to check if the string// is palindromefunction checkPalindrome($s){    for ($i = 0; $i < strlen($s); $i++)    {        if($s[$i] != $s[strlen($s) - $i - 1])            return false;    }    return true;} // Function that checks whether all the// palindromic sub-strings are of odd length.function CheckOdd($s){    $n = strlen($s);    for ($i = 0; $i < $n; $i++)    {                 // Creating each substring        $x = "";        for ($j = $i; $j < $n; $j++)        {            $x = $x.$s[$i];                         // If the sub-string is            // of even length and            // is a palindrome then,            // we return False            if(strlen($x) % 2 == 0 &&            checkPalindrome($x) == true)                return false;        }    }             return true;} // Driver code$s = "geeksforgeeks";if(CheckOdd($s))    echo "YES";else    echo "NO";     // This code is contributed by ita_c?>
<script>// Javascript implementation of the approach // Function to check if// the string is palindromefunction  checkPalindrome(s){    for (let i = 0; i < s.length; i++)    {        if(s[i] != s[(s.length - i - 1)])            return false;    }    return true;} // Function that checks whether// all the palindromic// sub-strings are of odd length.function CheckOdd(s){    let n = s.length;for (let i = 0; i < n; i++){           // Creating each substring    let x = "";    for (let j = i; j < n; j++)    {        x += s[j];                   // If the sub-string is        // of even length and        // is a palindrome then,        // we return False        if(x.length % 2 == 0 &&           checkPalindrome(x) == true)            return false;        }    }           return true;} // Driver codelet s = "geeksforgeeks";if(CheckOdd(s))    document.write("YES");else    document.write("NO");  // This code is contributed by rag2127</script>
NO
 
Time Complexity: O(N)Space Complexity: O(1)
andrew1234
29AjayKumar
Shashank_Sharma
ukasp
adityajaiswal
vaibhavaanand361
avanitrachhadiya2155
rag2127
palindrome
substring
Technical Scripter 2018
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Reverse words in a given string
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews