Palindrome Substrings Count
Last Updated :
11 Sep, 2024
Given a string, the task is to count all palindrome sub string in a given string. Length of palindrome sub string is greater than or equal to 2.
Examples:
Input : s = “abaab”
Output: 3
Explanation : Palindrome substrings (of length > 1) are “aba” , “aa” , “baab”
Input : s = “aaa”
Output: 3
Explanation : Palindrome substring (of length > 1) are “aa” , “aa” , “aaa”
Input : s = “abbaeae”
Output: 4
Explanation : Palindrome substring (of length > 1) are “bb” , “abba” , “aea”, “eae”
Naive Solution – O(n^3) Time
- Consider all possible substrings from index i to j by running nested loops.
- For every substring from i to j, check if it is palindrome.
C++
#include<bits/stdc++.h>
using namespace std;
// Function to check if the substring from i to j is a palindrome
bool isPal(string& s, int i, int j) {
while (i < j) {
if (s[i] != s[j]) return false;
i++;
j--;
}
return true;
}
// Counts palindromic substrings of length more than 2
int countPS(string& s) {
int n = s.length();
// Consider all possible substrings of lengths
// more than 1
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if (isPal(s, i, j)) { // Is Palindrome
res++;
}
}
}
return res;
}
// Driver code
int main() {
string s = "aaa";
cout << countPS(s);
return 0;
}
Java
public class GfG {
// Function to check if the substring from i to j
// is a palindrome
public static boolean isPal(String s, int i, int j) {
while (i < j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
// Counts palindromic substrings of length more than 2
public static int countPS(String s) {
int n = s.length();
int res = 0;
// Consider all possible substrings of
// length greater than 1
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (isPal(s, i, j)) {
res++;
}
}
}
return res;
}
// Driver code
public static void main(String[] args) {
String s = "aaa";
System.out.println(countPS(s)); // Output: 3
}
}
Python
# Function to check if the substring from i to j
# is a palindrome
def isPal(s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
# Counts palindromic substrings of length more than 2
def countPS(s):
n = len(s)
res = 0
# Consider all possible substrings of length
# greater than 1
for i in range(n):
for j in range(i + 1, n):
if isPal(s, i, j):
res += 1
return res
# Driver code
if __name__ == "__main__":
s = "aaa"
print(countPS(s)) # Output: 3
Memoization – O(n^2) Time
If we take a closer look, we can notice that we are checking same substrings for palindrome again and again. Imagine a recursive isPal(i, j) function that calls for isPal(i + i, j-1) if the last two characters match.
bool isPal(s, i, j) {
// Base case: if i crosses j or
// they’re the same, it’s a palindrome
if (i >= j) return true;
// Check if the characters at i and j are equal and
// recursively check for the substring in between
return (s[i] == s[j]) && isPal(s, i + 1, j – 1);
}
We can avoid recomputing overlapping Subproblems by making a 2D array memo.
- Size of the memo is going to be n x n as both staring and ending indexes range from 0 to n-1
- memo[i][j] = true if substring from i to j is palindrome, and false otherwise
- Before checking any substring for palindrom, we do a lookup in the memo table.
C++
#include<bits/stdc++.h>
using namespace std;
// Function to use memoization to check if a
// substring is palindrome
bool isPal(int i, int j, string& s, vector<vector<int>>& memo) {
if (i >= j) return true;
// If current substring is already checked
if (memo[i][j] != -1) return memo[i][j];
// Check if the characters at i and j are equal and the
// substring inside is palindrome
memo[i][j] = (s[i] == s[j] && isPal(i + 1, j - 1, s, memo));
return memo[i][j];
}
// Counts palindromic substrings of length more than 1
int countPS(string& s) {
int n = s.length();
// Memoization table
vector<vector<int>> memo(n, vector<int>(n, -1));
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the substring is palindrome
if (isPal(i, j, s, memo)) {
res++;
}
}
}
return res;
}
// Driver code
int main() {
string s = "aaa";
cout << countPS(s);
return 0;
}
Java
import java.util.Arrays;
public class PalindromeSubstringsMemo {
// Function to use memoization to check if a substring
// is palindrome
public static boolean isPal(int i, int j, String s,
int[][] memo) {
// Base case: single character or empty substring
if (i >= j) return true;
// If current substring is already checked
if (memo[i][j] != -1) return memo[i][j] == 1;
// Check if characters at i and j are equal
// and substring inside is palindrome
memo[i][j] = (s.charAt(i) == s.charAt(j) &&
isPal(i + 1, j - 1, s, memo)) ? 1 : 0;
return memo[i][j] == 1;
}
// Function to count palindromic substrings of length more than 1
public static int countPS(String s) {
int n = s.length();
// Memoization table
int[][] memo = new int[n][n];
for (int[] row : memo) {
Arrays.fill(row, -1); // Initialize the memo table to -1
}
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// Check if the substring is palindrome
if (isPal(i, j, s, memo)) {
res++;
}
}
}
return res;
}
// Driver code
public static void main(String[] args) {
String s = "aaa";
System.out.println(countPS(s)); // Output: 3
}
}
Python
def isPal(i, j, s, memo):
# Base case: single character or empty substring
if i >= j:
return True
# If current substring is already checked
if memo[i][j] != -1:
return memo[i][j] == 1
# Check if the characters at i and j are equal
# and substring inside is palindrome
memo[i][j] = 1 if (s[i] == s[j] and
isPal(i + 1, j - 1, s, memo)) else 0
return memo[i][j] == 1
# Function to count palindromic substrings
# of length more than 1
def countPS(s: str) -> int:
n = len(s)
# Memoization table
memo = [[-1] * n for _ in range(n)]
res = 0
for i in range(n):
for j in range(i + 1, n):
# Check if the substring is palindrome
if isPal(i, j, s, memo):
res += 1
return res
# Driver code
if __name__ == "__main__":
s = "aaa"
print(countPS(s)) # Output: 3
Time Complexity: O(n3)
Auxiliary Space: O(n2)
Bottom-Up DP – O(n^2) Time
We create a dp array of size n x n. The main point to note here is, we cannot simply fill the dp table from i = 0 to n-1 and then j from i to n – 1. To fill an entry (i, j), we would need value of (i+1, j-1). Like Matrix Chain Multiplication, we need to fill values in diagonal manner using gap variable.
- We first fill the main diagnoal or gap = 0 (or i = j) as we know a single character string is palindrome.
- Then we fill for gap = 1 (or j = i+1). If s[i] and s[j] are same, then answer is true, else false
- Then we fill remaining entries using results of dp[i+1][j-1]
C++
#include <bits/stdc++.h>
using namespace std;
// Returns total number of palindrome substrings of
// length greater than or equal to 2
int countPS(string& s) {
int n = s.length();
int res = 0;
// dp[i][j] = true if substring s[i..j] is a palindrome
vector<vector<bool>> dp(n, vector<bool>(n, false));
// Palindromes of single length, gap = 0
for (int i = 0; i < n; i++) {
dp[i][i] = true;
}
// Explicitly handle the case where gap = 1 (substrings of length 2)
for (int i = 0; i < n - 1; i++) {
if (s[i] == s[i + 1]) {
dp[i][i + 1] = true;
res++;
}
}
// Handle palindromes of length greater than 2 (gap >= 2)
for (int gap = 2; gap <= n; gap++) {
for (int i = 0; i <= n - gap; i++) {
int j = i + gap;
// Check if the current string is a palindrome
if (s[i] == s[j] && dp[i + 1][j - 1]) {
dp[i][j] = true;
res++;
}
}
}
return res;
}
// Driver code
int main() {
string s = "aaa";
cout << countPS(s) << endl;
return 0;
}
Java
import java.util.Arrays;
public class GfG {
// Returns total number of palindrome
// substrings of length greater than or equal to 2
public static int countPS(String s) {
int n = s.length();
int res = 0;
// dp[i][j] = true if substring s[i..j] is a palindrome
boolean[][] dp = new boolean[n][n];
// Palindromes of single length, gap = 0
for (int i = 0; i < n; i++) {
dp[i][i] = true;
}
// Explicitly handle the case where gap = 1
// (substrings of length 2)
for (int i = 0; i < n - 1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
dp[i][i + 1] = true;
res++;
}
}
// Handle palindromes of length greater than 2 (gap >= 2)
for (int gap = 2; gap < n; gap++) {
for (int i = 0; i <= n - gap - 1; i++) {
int j = i + gap;
// Check if the current string is a palindrome
if (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]) {
dp[i][j] = true;
res++;
}
}
}
return res;
}
// Driver code
public static void main(String[] args) {
String s = "aaa";
System.out.println(countPS(s));
}
}
Python
def countPS(s: str) -> int:
n = len(s)
res = 0
# dp[i][j] = True if substring s[i..j] is a palindrome
dp = [[False] * n for _ in range(n)]
# Palindromes of single length, gap = 0
for i in range(n):
dp[i][i] = True
# Explicitly handle the case where gap = 1
# (substrings of length 2)
for i in range(n - 1):
if s[i] == s[i + 1]:
dp[i][i + 1] = True
res += 1
# Handle palindromes of length greater than 2 (gap >= 2)
for gap in range(2, n):
for i in range(n - gap):
j = i + gap
# Check if the current string is a palindrome
if s[i] == s[j] and dp[i + 1][j - 1]:
dp[i][j] = True
res += 1
return res
# Driver code
if __name__ == "__main__":
s = "aaa"
print(countPS(s))
Time Complexity: O(n2)
Auxiliary Space: O(n2)
Using Center Expansion:
We can further optimize using the idea of center expansion. We have used this idea in Longest Palindromic Substring also. With this basic idea we can solve this problem in O(n^2) time and O(1) Space. We can further enhance it to work in linear time. Please refer Count All Palindrome Sub-Strings using Center Expansion for details
Related Articles:
Find all distinct palindromic sub-strings of a given string
Please Login to comment...