Count special palindromes in a String
Last Updated :
04 Aug, 2022
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"
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>
Time Complexity : O(n)
Auxiliary Space : O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem