Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Count special palindromes in a String
Next article icon

Count special palindromes in a String

Last Updated : 04 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a String s, count all special palindromic substrings of size greater than 1. A Substring is called special palindromic substring if all the characters in the substring are same or only the middle character is different for odd length. Example "aabaa" and "aaa" are special palindromic substrings and "abcba" is not special palindromic substring.

Examples : 

Input :  str = " abab" Output : 2 All Special Palindromic  substring are: "aba", "bab"  Input : str = "aabbb" Output : 4 All Special substring are: "aa", "bb", "bbb", "bb"
Recommended Practice
count special palindromic
Try It!

Simple Solution is that we simply generate all substrings one-by-one and count how many substring are Special Palindromic substring. This solution takes O(n3) time.

Efficient Solution 

There are 2 Cases : 

  • Case 1: All Palindromic substrings have same character : 
    We can handle this case by simply counting the same continuous character and using formula K*(K+1)/2 (total number of substring possible : Here K is count of Continuous same char). 
 Lets Str = "aaabba"  Traverse string from left to right and Count of same char   "aaabba"  =  3, 2, 1    for "aaa" : total substring possible are    'aa' 'aa', 'aaa', 'a', 'a', 'a'  : 3(3+1)/2 = 6     "bb" : 'b', 'b', 'bb' : 2(2+1)/2 = 3    'a'  : 'a' : 1(1+1)/2 = 1 
  • Case 2: We can handle this case by storing count of same character in another temporary array called "sameChar[n]" of size n. and pick each character one-by-one and check its previous and forward character are equal or not if equal then there are min_between( sameChar[previous], sameChar[forward] ) substring possible. 
Let's Str = "aabaaab"  Count of smiler char from left to right :  that we will store in Temporary array "sameChar"   Str         =    " a a b a a a b " sameChar[]  =      2 2 1 3 3 3 1 According to the problem statement middle character is different: so we have only left with char "b" at index :2 ( index from 0 to n-1) substring : "aabaaa" so only two substring are possible : "aabaa", "aba" that is min (smilerChar[index-1], smilerChar[index+1] ) that is 2.

Below is the implementation of above idea 

C++
// C++ program to count special Palindromic substring #include <bits/stdc++.h> using namespace std;  // Function to count special Palindromic substring int CountSpecialPalindrome(string str) {     int n = str.length();      // store count of special Palindromic substring     int result = 0;      // it will store the count of continues same char     int sameChar[n] = { 0 };      int i = 0;      // traverse string character from left to right     while (i < n) {          // store same character count         int sameCharCount = 1;          int j = i + 1;          // count similar character         while (str[i] == str[j] && j < n)             sameCharCount++, j++;          // Case : 1         // so total number of substring that we can         // generate are : K *( K + 1 ) / 2         // here K is sameCharCount         result += (sameCharCount * (sameCharCount + 1) / 2);          // store current same char count in sameChar[]         // array         sameChar[i] = sameCharCount;          // increment i         i = j;     }      // Case 2: Count all odd length Special Palindromic     // substring     for (int j = 1; j < n; j++)     {         // if current character is equal to previous         // one then we assign Previous same character         // count to current one         if (str[j] == str[j - 1])             sameChar[j] = sameChar[j - 1];          // case 2: odd length         if (j > 0 && j < (n - 1) &&             (str[j - 1] == str[j + 1] &&              str[j] != str[j - 1]))             result += min(sameChar[j - 1],                           sameChar[j + 1]);     }      // subtract all single length substring     return result - n; }  // driver program to test above fun int main() {     string str = "abccba";     cout << CountSpecialPalindrome(str) << endl;     return 0; } 
Java
// Java program to count special // Palindromic substring import java.io.*; import java.util.*; import java.lang.*;  class GFG {      // Function to count special // Palindromic substring public static int CountSpecialPalindrome(String str) {     int n = str.length();      // store count of special     // Palindromic substring     int result = 0;      // it will store the count      // of continues same char     int[] sameChar = new int[n];     for(int v = 0; v < n; v++)     sameChar[v] = 0;      int i = 0;      // traverse string character     // from left to right     while (i < n)      {          // store same character count         int sameCharCount = 1;          int j = i + 1;          // count similar character         while (j < n &&              str.charAt(i) == str.charAt(j))         {             sameCharCount++;             j++;         }          // Case : 1         // so total number of          // substring that we can         // generate are : K *( K + 1 ) / 2         // here K is sameCharCount         result += (sameCharCount *                    (sameCharCount + 1) / 2);          // store current same char          // count in sameChar[] array         sameChar[i] = sameCharCount;          // increment i         i = j;     }      // Case 2: Count all odd length     //           Special Palindromic     //           substring     for (int j = 1; j < n; j++)     {         // if current character is          // equal to previous one          // then we assign Previous          // same character count to         // current one         if (str.charAt(j) == str.charAt(j - 1))             sameChar[j] = sameChar[j - 1];          // case 2: odd length         if (j > 0 && j < (n - 1) &&         (str.charAt(j - 1) == str.charAt(j + 1) &&              str.charAt(j) != str.charAt(j - 1)))             result += Math.min(sameChar[j - 1],                                sameChar[j + 1]);     }      // subtract all single      // length substring     return result - n; }  // Driver code public static void main(String args[]) {     String str = "abccba";     System.out.print(CountSpecialPalindrome(str)); } }  // This code is contributed // by Akanksha Rai(Abby_akku) 
Python3
# Python3 program to count special # Palindromic substring  # Function to count special  # Palindromic substring def CountSpecialPalindrome(str):     n = len(str);      # store count of special     # Palindromic substring     result = 0;      # it will store the count      # of continues same char     sameChar=[0] * n;      i = 0;      # traverse string character      # from left to right     while (i < n):          # store same character count         sameCharCount = 1;          j = i + 1;          # count smiler character         while (j < n):             if(str[i] != str[j]):                 break;             sameCharCount += 1;             j += 1;                  # Case : 1         # so total number of substring          # that we can generate are :         # K *( K + 1 ) / 2         # here K is sameCharCount         result += int(sameCharCount *                       (sameCharCount + 1) / 2);          # store current same char          # count in sameChar[] array         sameChar[i] = sameCharCount;          # increment i         i = j;      # Case 2: Count all odd length      # Special Palindromic substring     for j in range(1, n):                  # if current character is equal          # to previous one then we assign          # Previous same character count          # to current one         if (str[j] == str[j - 1]):             sameChar[j] = sameChar[j - 1];          # case 2: odd length         if (j > 0 and j < (n - 1) and             (str[j - 1] == str[j + 1] and              str[j] != str[j - 1])):             result += (sameChar[j - 1]                     if(sameChar[j - 1] < sameChar[j + 1])                      else sameChar[j + 1]);      # subtract all single     # length substring     return result-n;  # Driver Code str = "abccba"; print(CountSpecialPalindrome(str));  # This code is contributed by mits. 
C#
// C# program to count special // Palindromic substring using System;  class GFG {      // Function to count special // Palindromic substring public static int CountSpecialPalindrome(String str) {     int n = str.Length;      // store count of special     // Palindromic substring     int result = 0;      // it will store the count      // of continues same char     int[] sameChar = new int[n];     for(int v = 0; v < n; v++)     sameChar[v] = 0;      int i = 0;      // traverse string character     // from left to right     while (i < n)      {          // store same character count         int sameCharCount = 1;          int j = i + 1;          // count smiler character         while (j < n &&                 str[i] == str[j])         {             sameCharCount++;             j++;         }          // Case : 1         // so total number of          // substring that we can         // generate are : K *( K + 1 ) / 2         // here K is sameCharCount         result += (sameCharCount *                    (sameCharCount + 1) / 2);          // store current same char          // count in sameChar[] array         sameChar[i] = sameCharCount;          // increment i         i = j;     }      // Case 2: Count all odd length     //         Special Palindromic     //         substring     for (int j = 1; j < n; j++)     {         // if current character is          // equal to previous one          // then we assign Previous          // same character count to         // current one         if (str[j] == str[j - 1])             sameChar[j] = sameChar[j - 1];          // case 2: odd length         if (j > 0 && j < (n - 1) &&            (str[j - 1] == str[j + 1] &&             str[j] != str[j - 1]))             result += Math.Min(sameChar[j - 1],                               sameChar[j + 1]);     }      // subtract all single      // length substring     return result - n; }  // Driver code public static void Main() {     String str = "abccba";     Console.Write(CountSpecialPalindrome(str)); } }  // This code is contributed by mits. 
PHP
<?php // PHP program to count special // Palindromic substring  // Function to count special  // Palindromic substring function CountSpecialPalindrome($str) {     $n = strlen($str);      // store count of special     // Palindromic substring     $result = 0;      // it will store the count      // of continues same char     $sameChar=array_fill(0, $n, 0);      $i = 0;      // traverse string character      // from left to right     while ($i < $n)      {          // store same character count         $sameCharCount = 1;          $j = $i + 1;          // count smiler character         while ($j < $n)         {             if($str[$i] != $str[$j])             break;             $sameCharCount++;             $j++;         }                  // Case : 1         // so total number of substring          // that we can generate are :         // K *( K + 1 ) / 2         // here K is sameCharCount         $result += (int)($sameCharCount *                          ($sameCharCount + 1) / 2);          // store current same char          // count in sameChar[] array         $sameChar[$i] = $sameCharCount;          // increment i         $i = $j;     }      // Case 2: Count all odd length      // Special Palindromic substring     for ($j = 1; $j < $n; $j++)     {         // if current character is equal          // to previous one then we assign          // Previous same character count          // to current one         if ($str[$j] == $str[$j - 1])             $sameChar[$j] = $sameChar[$j - 1];          // case 2: odd length         if ($j > 0 && $j < ($n - 1) &&             ($str[$j - 1] == $str[$j + 1] &&                 $str[$j] != $str[$j - 1]))             $result += $sameChar[$j - 1] <                         $sameChar[$j + 1] ?                         $sameChar[$j - 1] :                         $sameChar[$j + 1];     }      // subtract all single     // length substring     return $result - $n; }  // Driver Code $str = "abccba"; echo CountSpecialPalindrome($str);  // This code is contributed by mits. ?> 
JavaScript
<script>       // JavaScript program to count special Palindromic substring        // Function to count special Palindromic substring       function CountSpecialPalindrome(str) {         var n = str.length;          // store count of special Palindromic substring         var result = 0;          // it will store the count of continues same char         var sameChar = [...Array(n)];          var i = 0;          // traverse string character from left to right         while (i < n) {           // store same character count           var sameCharCount = 1;            var j = i + 1;            // count smiler character           while (str[i] == str[j] && j < n) sameCharCount++, j++;            // Case : 1           // so total number of substring that we can           // generate are : K *( K + 1 ) / 2           // here K is sameCharCount           result += (sameCharCount * (sameCharCount + 1)) / 2;            // store current same char count in sameChar[]           // array           sameChar[i] = sameCharCount;            // increment i           i = j;         }          // Case 2: Count all odd length Special Palindromic         // substring         for (var j = 1; j < n; j++) {           // if current character is equal to previous           // one then we assign Previous same character           // count to current one           if (str[j] == str[j - 1]) sameChar[j] = sameChar[j - 1];            // case 2: odd length           if (             j > 0 &&             j < n - 1 &&             str[j - 1] == str[j + 1] &&             str[j] != str[j - 1]           )             result += Math.min(sameChar[j - 1], sameChar[j + 1]);         }          // subtract all single length substring         return result - n;       }        // driver program to test above fun       var str = "abccba";       document.write(CountSpecialPalindrome(str) + "<br>");     </script> 

Output
1 

Time Complexity : O(n) 
Auxiliary Space : O(n)


Next Article
Count special palindromes in a String

N

Nishant_Singh
Improve
Article Tags :
  • Misc
  • Strings
  • DSA
  • palindrome
Practice Tags :
  • Misc
  • palindrome
  • Strings

Similar Reads

    Palindrome Substrings Count
    Given a string s, the task is to count all palindromic substrings of length more than one.Examples:Input: s = "abaab"Output: 3Explanation: Palindromic substrings with length greater than 1, are "aba", "aa", and "baab".Input: s = "aaa"Output: 3Explanation: Palindromic substrings with length greater t
    15+ min read
    Count palindrome words in a sentence
    Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
    5 min read
    Count maximum-length palindromes in a String
    Given a string, count how many maximum-length palindromes are present. (It need not be a substring) Examples: Input : str = "ababa" Output: 2 Explanation : palindromes of maximum of lengths are : "ababa", "baaab" Input : str = "ababab" Output: 4 Explanation : palindromes of maximum of lengths are :
    9 min read
    Count Palindromic Substrings in a Binary String
    Given a binary string S i.e. which consists only of 0's and 1's. Calculate the number of substrings of S which are palindromes. String S contains at most two 1's. Examples: Input: S = "011"Output: 4Explanation: "0", "1", "1" and "11" are the palindromic substrings. Input: S = "0" Output: 1Explanatio
    7 min read
    Palindrome String Coding Problems
    A string is called a palindrome if the reverse of the string is the same as the original one.Example: “madam”, “racecar”, “12321”.Palindrome StringProperties of a Palindrome String:A palindrome string has some properties which are mentioned below:A palindrome string has a symmetric structure which m
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences