The Wayback Machine - https://web.archive.org/web/20240919053040/https://www.geeksforgeeks.org/count-palindromic-characteristics-string/
Open In App

Count palindromic characteristics of a String

Last Updated : 02 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string s of length n, count the number of substrings having different types of palindromic characteristics. 
Palindromic Characteristic is the number of k-palindromes in a string where k lies in range [0, n). 

A string is 1-palindrome(or simply palindrome) if and only if it reads the same backward as it reads forward. 
A string is k-palindrome (k > 1) if and only if : 

  1. Its left half is equal to its right half. 
  2. Its left half and right half should be non-empty (k – 1)-palindrome. The left half of a string of length ‘t’ is its prefix of length ?t/2?, and the right half is the suffix of the same length. 

Note: Each substring is counted as many times as it appears in the string. For example, in the string “aaa” the substring “a” appears 3 times.

Examples :

Input : abba
Output : 6 1 0 0
Explanation : 
"6" 1-palindromes = "a", "b", "b", "a", "bb", "abba".
"1" 2-palindrome = "bb". Because "b" is 1-palindrome 
and "bb" has both left and right parts equal. 
"0" 3-palindrome and 4-palindrome.

Input : abacaba
Output : 12 4 1 0 0 0 0
Explanation : 
"12" 1-palindromes = "a", "b", "a", "c", "a", "b", 
"a", "aba", "aca", "aba", "bacab", "abacaba".
"4" 2-palindromes = "aba", "aca", "aba", "abacaba". 
Because "a" and "aba" are 1-palindromes.

NOTE :  "bacab" is not 2-palindrome as "ba" 
is not 1-palindrome. "1" 3-palindrome = "abacaba". 
Because is "aba" is 2-palindrome. "0" other 
k-palindromes where 4 < = k < = 7.

Approach: 

Take a string s and say it is a 1-palindrome and checking its left half also turns out to be a 1-palindrome then, obviously its right part will always be equal to the left part (as the string is also a 1-palindrome) making the original string to be 2-palindrome. 

Now, similarly, checking the left half of the string, it also turns out to be a 1-palindrome then it will make the left half to be 2-palindrome and hence, making the original string to be 3-palindrome and so on checking it till only 1 alphabet is left or the part is not a 1-palindrome. 

Let’s take string = “abacaba”. As known “abacaba” is 1-palindrome. So, when checking for its left half “aba”, which is also a 1-palindrome, it makes “abacaba” a 2-palindrome. Then, check for “aba”‘s left half “a” which is also a 1-palindrome. So it makes “aba” a 2-palindrome and “aba” makes “abacaba” a 3-palindrome. So in other words, if a string is a k-palindrome then it is also a (k-1)-palindrome, (k-2)-palindrome, and so on till 1-palindrome. Code for the same is given below which firsts check each and every substring if it is a palindrome or not and then counts the number of k-palindromic substrings recursively in logarithmic time. 

Below is the implementation of above approach :  

C++

// A C++ program which counts different
// palindromic characteristics of a string.
#include <bits/stdc++.h>
using namespace std;
 
const int MAX_STR_LEN = 1000;
 
bool P[MAX_STR_LEN][MAX_STR_LEN];
int Kpal[MAX_STR_LEN];
 
// A C++ function which checks whether a
// substring str[i..j] of a given string
// is a palindrome or not.
void checkSubStrPal(string str, int n)
{
 
    // P[i][j] = true if substring str
    // [i..j] is palindrome, else false
    memset(P, false, sizeof(P));
 
    // palindrome of single length
    for (int i = 0; i < n; i++)
        P[i][i] = true;
 
    // palindrome of length 2
    for (int i = 0; i < n - 1; i++)
        if (str[i] == str[i + 1])
            P[i][i + 1] = true;
 
    // Palindromes of length more than 2.
    // This loop is similar to Matrix Chain
    // Multiplication. We start with a gap of
    // length 2 and fill P table in a way that
    // gap between starting and ending indexes
    // increases one by one by outer loop.
    for (int gap = 2; gap < n; gap++)
    {
 
        // Pick starting point for current gap
        for (int i = 0; i < n - gap; i++)
        {
 
            // Set ending point
            int j = gap + i;
 
            // If current string is palindrome
            if (str[i] == str[j] && P[i + 1][j - 1])
                P[i][j] = true;
        }
    }
}
 
// A C++ function which recursively
// counts if a string str [i..j] is
// a k-palindromic string or not.
void countKPalindromes(int i, int j, int k)
{
    // terminating condition for a
    // string which is a k-palindrome.
    if (i == j)
    {
        Kpal[k]++;
        return;
    }
 
    // terminating condition for a
    // string which is not a k-palindrome.
    if (P[i][j] == false)
        return;
 
    // increases the counter for the
    // string if it is a k-palindrome.
    Kpal[k]++;
 
    // mid is middle pointer of
    // the string str [i...j].
    int mid = (i + j) / 2;
 
    // if length of string which is
    // (j - i + 1) is odd than we have
    // to subtract one from mid.
    // else if even then no change.
    if ((j - i + 1) % 2 == 1)
        mid--;
 
    // if the string is k-palindrome
    // then we check if it is a
    // (k+1) - palindrome or not by
    // just sending any of one half of
    // the string to the Count_k_Palindrome
    // function.
    countKPalindromes(i, mid, k + 1);
}
 
void printKPalindromes(string s)
{
 
    // Count of k-palindromes is equal
    // to zero initially.
    memset(Kpal, 0, sizeof(Kpal));
 
    // Finding all palindromic
    // substrings of given string
    int n = s.length();
    checkSubStrPal(s, n);
 
    // counting k-palindromes for each and
    // every substring of given string. .
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n - i; j++)
            countKPalindromes(j, j + i, 1);
 
    // Output the number of K-palindromic
    // substrings of a given string.
    for (int i = 1; i <= n; i++)
        cout << Kpal[i] << " ";
    cout << "\n";
}
 
// Driver code
int main()
{
    string s = "abacaba";
    printKPalindromes(s);
    return 0;
}

                    

Java

// Java program which counts
// different palindromic
// characteristics of a string.        
import java.io.*;
 
class GFG
{
    static int MAX_STR_LEN = 1000;
     
    static boolean P[][] =
           new boolean[MAX_STR_LEN][MAX_STR_LEN];
    static int []Kpal =
           new int[MAX_STR_LEN];
     
    // function which checks
    // whether a substring
    // str[i..j] of a given
    // string is a palindrome or not.
    static void checkSubStrPal(String str,
                               int n)
    {
     
        // P[i,j] = true if substring
        // str [i..j] is palindrome,
        // else false
        for (int i = 0; i < MAX_STR_LEN; i++)
        {
            for (int j = 0; j < MAX_STR_LEN; j++)
                P[i][j] = false;
            Kpal[i] = 0;
        }
         
        // palindrome of
        // single length
        for (int i = 0; i < n; i++)
            P[i][i] = true;
     
        // palindrome of
        // length 2
        for (int i = 0; i < n - 1; i++)
            if (str.charAt(i) == str.charAt(i + 1))
                P[i][i + 1] = true;
     
        // Palindromes of length
        // more than 2. This loop
        // is similar to Matrix
        // Chain Multiplication.
        // We start with a gap of
        // length 2 and fill P table
        // in a way that gap between
        // starting and ending indexes
        // increases one by one by
        // outer loop.
        for (int gap = 2; gap < n; gap++)
        {
     
            // Pick starting point
            // for current gap
            for (int i = 0; i < n - gap; i++)
            {
     
                // Set ending point
                int j = gap + i;
     
                // If current string
                // is palindrome
                if (str.charAt(i) == str.charAt(j) &&
                                     P[i + 1][j - 1])
                    P[i][j] = true;
            }
        }
    }
     
    // A function which recursively
    // counts if a string str [i..j] is
    // a k-palindromic string or not.
    static void countKPalindromes(int i, int j,
                                  int k)
    {
        // terminating condition
        // for a string which is
        // a k-palindrome.
        if (i == j)
        {
            Kpal[k]++;
            return;
        }
     
        // terminating condition for
        // a string which is not a
        // k-palindrome.
        if (P[i][j] == false)
            return;
     
        // increases the counter
        // for the string if it
        // is a k-palindrome.
        Kpal[k]++;
     
        // mid is middle pointer of
        // the string str [i...j].
        int mid = (i + j) / 2;
     
        // if length of string which
        // is (j - i + 1) is odd than
        // we have to subtract one
        // from mid else if even then
        // no change.
        if ((j - i + 1) % 2 == 1)
            mid--;
     
        // if the string is k-palindrome
        // then we check if it is a
        // (k+1) - palindrome or not
        // by just sending any of one
        // half of the string to the
        // Count_k_Palindrome function.
        countKPalindromes(i, mid, k + 1);
    }
     
    static void printKPalindromes(String s)
    {
        // Finding all palindromic
        // substrings of given string
        int n = s.length();
        checkSubStrPal(s, n);
     
        // counting k-palindromes for
        // each and every substring
        // of given string. .
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n - i; j++)
                countKPalindromes(j, j + i, 1);
     
        // Output the number of
        // K-palindromic substrings
        // of a given string.
        for (int i = 1; i <= n; i++)
            System.out.print(Kpal[i] + " ");
        System.out.println();
    }
     
    // Driver code
    public static void main(String args[])
    {
        String s = "abacaba";
        printKPalindromes(s);
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)

                    

Python3

# Python program which counts
# different palindromic
# characteristics of a string.        
MAX_STR_LEN = 1000;
 
P = [[0 for x in range(MAX_STR_LEN)]
        for y in range(MAX_STR_LEN)] ;
 
for i in range(0, MAX_STR_LEN) :
    for j in range(0, MAX_STR_LEN) :
        P[i][j] = False;
         
Kpal = [0] * MAX_STR_LEN;
     
# def which checks
# whether a substr[i..j]
# of a given is a
# palindrome or not.
def checkSubStrPal(str, n) :
 
    global P, Kpal, MAX_STR_LEN;
             
    # P[i,j] = True if substr
    # [i..j] is palindrome,
    # else False
    for i in range(0, MAX_STR_LEN) :
 
        for j in range(0, MAX_STR_LEN) :
            P[i][j] = False;
        Kpal[i] = 0;
     
    # palindrome of
    # single length
    for i in range(0, n) :
        P[i][i] = True;
 
    # palindrome of
    # length 2
    for i in range(0, n - 1) :
        if (str[i] == str[i + 1]) :
            P[i][i + 1] = True;
 
    # Palindromes of length more
    # than 2. This loop is similar
    # to Matrix Chain Multiplication.
    # We start with a gap of length
    # 2 and fill P table in a way
    # that gap between starting and
    # ending indexes increases one
    # by one by outer loop.
    for gap in range(2, n) :
 
        # Pick starting point
        # for current gap
        for i in range(0, n - gap) :
 
            # Set ending point
            j = gap + i;
 
            # If current string
            # is palindrome
            if (str[i] == str[j] and
                P[i + 1][j - 1]) :
                P[i][j] = True;
 
# A Python def which
# recursively counts if
# a str [i..j] is a
# k-palindromic or not.
def countKPalindromes(i, j, k) :
 
    global Kpal, P;
     
    # terminating condition
    # for a which is a
    # k-palindrome.
    if (i == j) :
     
        Kpal[k] = Kpal[k] + 1;
        return;
 
    # terminating condition
    # for a which is not a
    # k-palindrome.
    if (P[i][j] == False) :
        return;
 
    # increases the counter
    # for the if it is a
    # k-palindrome.
    Kpal[k] = Kpal[k] + 1;
 
    # mid is middle pointer
    # of the str [i...j].
    mid = int((i + j) / 2);
 
    # if length of which is
    # (j - i + 1) is odd than
    # we have to subtract one
    # from mid else if even
    # then no change.
    if ((j - i + 1) % 2 == 1) :
        mid = mid - 1;
 
    # if the is k-palindrome
    # then we check if it is a
    # (k+1) - palindrome or not
    # by just sending any of
    # one half of the to the
    # Count_k_Palindrome def.
    countKPalindromes(i, mid, k + 1);
 
def printKPalindromes(s) :
 
    global P, Kpal, MAX_STR_LEN;
             
    # Finding all palindromic
    # substrings of given string
    n = len(s);
    checkSubStrPal(s, n);
 
    # counting k-palindromes
    # for each and every sub
    # of given string. .
    for i in range(0, n) :
        for j in range(0, n - i) :
            countKPalindromes(j, j + i, 1);
 
    # Output the number of
    # K-palindromic substrings
    # of a given string.
    for i in range(1, n + 1) :
        print (Kpal[i], end=" ");
    print();
 
 
# Driver code
s = "abacaba";
printKPalindromes(s);
 
# This code is contributed by
# Manish Shaw(manishshaw1)

                    

C#

// C# program which counts
// different palindromic
// characteristics of a string.        
using System;
 
class GFG
{
    static int MAX_STR_LEN = 1000;
     
    static bool [,]P = new bool[MAX_STR_LEN,
                                MAX_STR_LEN];
    static int []Kpal = new int[MAX_STR_LEN];
     
    // function which checks whether
    // a substring str[i..j] of a
    // given string is a palindrome or not.
    static void checkSubStrPal(string str,
                               int n)
    {
     
        // P[i,j] = true if substring str
        // [i..j] is palindrome, else false
        for (int i = 0; i < MAX_STR_LEN; i++)
        {
            for (int j = 0; j < MAX_STR_LEN; j++)
                P[i, j] = false;
            Kpal[i] = 0;
        }
         
        // palindrome of single length
        for (int i = 0; i < n; i++)
            P[i, i] = true;
     
        // palindrome of length 2
        for (int i = 0; i < n - 1; i++)
            if (str[i] == str[i + 1])
                P[i, i + 1] = true;
     
        // Palindromes of length more
        // than 2. This loop is similar
        // to Matrix Chain Multiplication.
        // We start with a gap of length 2
        // and fill P table in a way that
        // gap between starting and ending
        // indexes increases one by one by
        // outer loop.
        for (int gap = 2; gap < n; gap++)
        {
     
            // Pick starting point
            // for current gap
            for (int i = 0; i < n - gap; i++)
            {
     
                // Set ending point
                int j = gap + i;
     
                // If current string
                // is palindrome
                if (str[i] == str[j] &&
                        P[i + 1, j - 1])
                    P[i, j] = true;
            }
        }
    }
     
    // A C++ function which recursively
    // counts if a string str [i..j] is
    // a k-palindromic string or not.
    static void countKPalindromes(int i, int j,
                                  int k)
    {
        // terminating condition for a
        // string which is a k-palindrome.
        if (i == j)
        {
            Kpal[k]++;
            return;
        }
     
        // terminating condition for
        // a string which is not a
        // k-palindrome.
        if (P[i, j] == false)
            return;
     
        // increases the counter for the
        // string if it is a k-palindrome.
        Kpal[k]++;
     
        // mid is middle pointer of
        // the string str [i...j].
        int mid = (i + j) / 2;
     
        // if length of string which is
        // (j - i + 1) is odd than we have
        // to subtract one from mid.
        // else if even then no change.
        if ((j - i + 1) % 2 == 1)
            mid--;
     
        // if the string is k-palindrome
        // then we check if it is a
        // (k+1) - palindrome or not
        // by just sending any of one
        // half of the string to the
        // Count_k_Palindrome function.
        countKPalindromes(i, mid, k + 1);
    }
     
    static void printKPalindromes(string s)
    {
        // Finding all palindromic
        // substrings of given string
        int n = s.Length;
        checkSubStrPal(s, n);
     
        // counting k-palindromes for each and
        // every substring of given string. .
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n - i; j++)
                countKPalindromes(j, j + i, 1);
     
        // Output the number of K-palindromic
        // substrings of a given string.
        for (int i = 1; i <= n; i++)
            Console.Write(Kpal[i] + " ");
        Console.WriteLine();
    }
     
    // Driver code
    static void Main()
    {
        string s = "abacaba";
        printKPalindromes(s);
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)

                    

PHP

<?php
// PHP program which counts
// different palindromic
// characteristics of a string.        
$MAX_STR_LEN = 1000;
 
$P = array(array());
$Kpal = array_fill(0, $MAX_STR_LEN, 0);
 
for($i = 0; $i < $MAX_STR_LEN; $i++)
{
    for($j = 0; $j < $MAX_STR_LEN; $j++)
        $P[$i][$j] = false;
}
     
// function which checks
// whether a substr[i..j]
// of a given is a
// palindrome or not.
function checkSubStrPal($str,
                        $n)
{
    global $P, $Kpal,
           $MAX_STR_LEN;
            
    // P[i,j] = true if substr
    // [i..j] is palindrome, else false
    for ($i = 0;
         $i < $MAX_STR_LEN; $i++)
    {
        for ($j = 0;
             $j < $MAX_STR_LEN; $j++)
            $P[$i][$j] = false;
        $Kpal[$i] = 0;
    }
     
    // palindrome of
    // single length
    for ($i = 0; $i < $n; $i++)
        $P[$i][$i] = true;
 
    // palindrome of
    // length 2
    for ($i = 0; $i < $n - 1; $i++)
        if ($str[$i] == $str[$i + 1])
            $P[$i][$i + 1] = true;
 
    // Palindromes of length more
    // than 2. This loop is similar
    // to Matrix Chain Multiplication.
    // We start with a gap of length
    // 2 and fill P table in a way
    // that gap between starting and
    // ending indexes increases one
    // by one by outer loop.
    for ($gap = 2; $gap < $n; $gap++)
    {
        // Pick starting point
        // for current gap
        for ($i = 0;
             $i < $n - $gap; $i++)
        {
            // Set ending point
            $j = $gap + $i;
 
            // If current string
            // is palindrome
            if ($str[$i] == $str[$j] &&
                    $P[$i + 1][$j - 1])
                $P[$i][$j] = true;
        }
    }
}
 
// A PHP function which
// recursively counts if
// a str [i..j] is a
// k-palindromic or not.
function countKPalindromes($i, $j, $k)
{
    global $Kpal, $P;
     
    // terminating condition for a
    // which is a k-palindrome.
    if ($i == $j)
    {
        $Kpal[$k]++;
        return;
    }
 
    // terminating condition
    // for a which is not a
    // k-palindrome.
    if ($P[$i][$j] == false)
        return;
 
    // increases the counter
    // for the if it is a
    // k-palindrome.
    $Kpal[$k]++;
 
    // mid is middle pointer
    // of the str [i...j].
    $mid = ($i + $j) / 2;
 
    // if length of which is
    // (j - i + 1) is odd than
    // we have to subtract one
    // from mid else if even
    // then no change.
    if (($j - $i + 1) % 2 == 1)
        $mid--;
 
    // if the is k-palindrome
    // then we check if it is a
    // (k+1) - palindrome or not
    // by just sending any of
    // one half of the to the
    // Count_k_Palindrome function.
    countKPalindromes($i, $mid,
                      $k + 1);
}
 
function printKPalindromes($s)
{
    global $P, $Kpal,
           $MAX_STR_LEN;
            
    // Finding all palindromic
    // substrings of given string
    $n = strlen($s);
    checkSubStrPal($s, $n);
 
    // counting k-palindromes
    // for each and every sub
    // of given string. .
    for ($i = 0; $i < $n; $i++)
        for ($j = 0; $j < $n - $i; $j++)
            countKPalindromes($j, $j +
                              $i, 1);
 
    // Output the number of
    // K-palindromic substrings
    // of a given string.
    for ($i = 1; $i <= $n; $i++)
        echo ($Kpal[$i] . " ");
    echo("\n");
}
 
// Driver code
$s = "abacaba";
printKPalindromes($s);
 
// This code is contributed by
// Manish Shaw(manishshaw1)
?>

                    

Javascript

// A javascript program which counts different
// palindromic characteristics of a string.
 
let MAX_STR_LEN = 1000;
 
let P = new Array(MAX_STR_LEN);
for(let i = 0; i < MAX_STR_LEN; i++){
    P[i] = new Array(MAX_STR_LEN);
}
 
let Kpal = new Array(MAX_STR_LEN);
 
// A JavaScript function which checks whether a
// substring str[i..j] of a given string
// is a palindrome or not.
function checkSubStrPal(str, n)
{
 
    // P[i][j] = true if substring str
    // [i..j] is palindrome, else false
    for(let i = 0; i < P.length; i++){
        for(let j = 0; j < P[0].length; j++){
            P[i][j] = false;
        }
    }
 
    // palindrome of single length
    for (let i = 0; i < n; i++)
        P[i][i] = true;
 
    // palindrome of length 2
    for (let i = 0; i < n - 1; i++)
        if (str[i] == str[i + 1])
            P[i][i + 1] = true;
 
    // Palindromes of length more than 2.
    // This loop is similar to Matrix Chain
    // Multiplication. We start with a gap of
    // length 2 and fill P table in a way that
    // gap between starting and ending indexes
    // increases one by one by outer loop.
    for (let gap = 2; gap < n; gap++)
    {
 
        // Pick starting point for current gap
        for (let i = 0; i < n - gap; i++)
        {
 
            // Set ending point
            let j = gap + i;
 
            // If current string is palindrome
            if (str[i] == str[j] && P[i + 1][j - 1])
                P[i][j] = true;
        }
    }
}
 
// A C++ function which recursively
// counts if a string str [i..j] is
// a k-palindromic string or not.
function countKPalindromes(i, j, k)
{
    // terminating condition for a
    // string which is a k-palindrome.
    if (i == j)
    {
        Kpal[k] = Kpal[k] + 1;
        return;
    }
 
    // terminating condition for a
    // string which is not a k-palindrome.
    if (P[i][j] == false)
        return;
 
    // increases the counter for the
    // string if it is a k-palindrome.
    Kpal[k] = Kpal[k] + 1;
 
    // mid is middle pointer of
    // the string str [i...j].
    let mid = Math.floor((i + j) / 2);
 
    // if length of string which is
    // (j - i + 1) is odd than we have
    // to subtract one from mid.
    // else if even then no change.
    if ((j - i + 1) % 2 == 1)
        mid = mid - 1;
 
    // if the string is k-palindrome
    // then we check if it is a
    // (k+1) - palindrome or not by
    // just sending any of one half of
    // the string to the Count_k_Palindrome
    // function.
    countKPalindromes(i, mid, k + 1);
}
 
function printKPalindromes(s)
{
 
    // Count of k-palindromes is equal
    // to zero initially.
    for(let i = 0; i < Kpal.length; i++){
        Kpal[i] = 0;
    }
 
    // Finding all palindromic
    // substrings of given string
    let n = s.length;
    checkSubStrPal(s, n);
 
    // counting k-palindromes for each and
    // every substring of given string. .
    for (let i = 0; i < n; i++)
        for (let j = 0; j < n - i; j++)
            countKPalindromes(j, j + i, 1);
 
    // Output the number of K-palindromic
    // substrings of a given string.
    for (let i = 1; i <= n; i++)
        console.log(Kpal[i] + " ");
}
 
// Driver code
let s = "abacaba";
printKPalindromes(s);

                    

Output
12 4 1 0 0 0 0 

Complexity Analysis:

  • Time Complexity : O(n^2$\log{n}$          ) 
  • Auxiliary Space : O(n^2          )


Previous Article
Next Article

Similar Reads

Minimum cuts required to convert a palindromic string to a different palindromic string
Given palindromic string s, the task is to find minimum k, such that you can cut this string into k+1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. If it is impossible then print -1.Examples: Input : string = "civic" Output : 2 Explanation : ci | v | ic --&gt; ic |
15+ min read
Make palindromic string non-palindromic by rearranging its letters
Given string str containing lowercase alphabets (a - z). The task is to print the string after rearranging some characters such that the string becomes non-palindromic. If it's impossible to make the string non-palindrome then print -1. Examples: Input: str = "abba" Output: aabb Input: str = "zzz" Output: -1 Brute Force: Iterate through all possibl
9 min read
Longest Palindromic Substring using Palindromic Tree | Set 3
Given a string, find the longest substring which is a palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”. Prerequisite : Palindromic Tree | Longest Palindromic Substring Structure of Palindromic Tree : The palindromic Tree’s actual structure is close to the directed graph. It is actually a merged s
15+ min read
Find the count of palindromic sub-string of a string in its sorted form
Given string str consisting of lowercase English alphabets, the task is to find the total number of palindromic sub-strings present in the sorted form of str. Examples: Input: str = "acbbd" Output: 6 All palindromic sub-string in it's sorted form ("abbcd") are "a", "b", "b", "bb", "c" and "d". Input: str = "abbabdbd" Output: 16 Naive approach: One
5 min read
Permutation of given string that maximizes count of Palindromic substrings
Given a string S, the task is to find the permutation of the string such that palindromic substrings in the string are maximum.Note: There can be multiple answers for each string. Examples: Input: S = "abcb" Output: "abbc" Explanation: "abbc" is the string with maximum number of palindromic substrings. Palindromic Substrings are - {"a", "b", "b", "
3 min read
Count pairs of non-overlapping palindromic sub-strings of the given string
Given a string S. The task is to count the non-overlapping pairs of palindromic sub-strings S1 and S2 such that the strings should be S1[L1...R1] and S2[L2...R2] where 0 ? L1 ? R1 &lt; L2 ? R2 &lt; N. The task is to count the number of pairs of the non-overlapping palindromic sub-strings. Examples: Input: s = "aaa" Output: 5 All possible pairs are
13 min read
Count of unique palindromic strings of length X from given string
Given a string s and an integer X, our task is to find the number of distinct palindromic strings of length X from the given string. Examples: Input: s = "aaa", X = 2 Output: 1 Explanation: Here all the characters of the string is the same so we can only make a one different string {aa} of length 2. Input: s = "aabaabbc", X = 3 Output: 6 Explanatio
9 min read
Count of pairs of strings whose concatenation forms a palindromic string
Given an array A[ ] consisting of N strings, the task is to count the number of pairs of possible strings that on merging forms a Palindromic String or can be rearranged to form a Palindromic String. Example : Input: N = 6, A[ ] = {aab, abcac, dffe, ed, aa, aade}Output: 6Explanation: All possible pairs of strings which generates a palindromic strin
9 min read
Minimum Count of Bit flips required to make a Binary String Palindromic
Given an integer N, the task is to find the minimum number of bits required to be flipped to convert the binary representation of N into a palindrome. Examples: Input: N = 12 Output: 2 Explanation: Binary String representing 12 = "1100". To make "1100" a palindrome, convert the string to "0110". Therefore, minimum bits required to be flipped is 2.I
7 min read
Count pairs of non overlapping Substrings of size K which form a palindromic String
Given a string S of length l, the task is to count the number of pairs of two non-overlapping substrings of length K of the string S, such that on joining the two non-overlapping substrings the resultant string is a palindrome. Examples: Input: S = "abcdbadc", K = 2Output: 2 Explanation: Possible substrings of length 2: ab, bc, cd, db, ba, ad, dc (
15 min read
Count all palindromic Substrings for each character in a given String
Given a string S of length n, for each character S[i], the task is to find the number of palindromic substrings of length K such that no substring should contain S[i], the task is to return an array A of length n, where A[i] is the count of palindromic substrings of length K which does not include the character S[i]. Examples: Input: S = "aababba",
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: 1Explanation: "0" is the only palindromic substring. Approach
7 min read
Count All Palindromic Subsequence in a given String
Find how many palindromic subsequences (need not necessarily be distinct) can be formed in a given string. Note that the empty string is not considered a palindrome.  Examples:  Input : str = "abcd"Output : 4Explanation :- palindromic subsequence are : "a" ,"b", "c" ,"d" Input : str = "aab"Output : 4Explanation :- palindromic subsequence are :"a",
15+ min read
Longest palindromic string formed by concatenation of prefix and suffix of a string
Given string str, the task is to find the longest palindromic substring formed by the concatenation of the prefix and suffix of the given string str. Examples: Input: str = "rombobinnimor" Output: rominnimor Explanation: The concatenation of string "rombob"(prefix) and "mor"(suffix) is "rombobmor" which is a palindromic string. The concatenation of
11 min read
Find a palindromic string B such that given String A is a subsequence of B
Given a string [Tex]A [/Tex]. Find a string [Tex]B [/Tex], 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 subsequence of "contest". A pali
6 min read
Minimum characters to be replaced to make a string concatenation of a K-length palindromic string
Given a string S of size N and a positive integer K ( where N % K = 0), the task is to find the minimum number of characters required to be replaced such that the string is K-periodic and the K-length periodic string must be a palindrome. Examples: Input: S = "abaaba", K = 3Output: 0Explanation: The given string is already K-periodic and the period
11 min read
Make a palindromic string from given string
Given a string S consisting of lower-case English alphabets only, we have two players playing the game. The rules are as follows: The player can remove any character from the given string S and write it on paper on any side(left or right) of an empty string.The player wins the game, if at any move he can get a palindromic string first of length
7 min read
Partition a string into palindromic strings of at least length 2 with every character present in a single string
Given a string S consisting of N lowercase alphabets, the task is to check if all the strings of at least length 2 formed by selecting every character of the string S only once are palindromic or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "abbbaddzcz"Output: YesExplanation: The palindromic strings of len
10 min read
Return a Palindromic String after removing minimum length Prefix from given String
Given a string B, the task is to find the minimum length prefix of the string which, when removed and added to the end of the string, will make the string a palindrome. Return the palindromic string. If no such string exists, we need to determine that. Examples: Input: "aabb"Output: "abba"Explanation: We can remove the prefix "a" from the string "a
5 min read
Check if a string contains a palindromic sub-string of even length
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 : aassssOutput : YESInput : gfgOutput : NOApproach: 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. Thi
8 min read
Check if a string can be made palindromic by swapping pairs of characters from indices having unequal characters in a Binary String
Given a string S and a binary string B, both of length N, the task is to check if the given string S can be made palindromic by repeatedly swapping characters at any pair of indices consisting of unequal characters in the string B. Examples: Input: S = "BAA", B = "100"Output: YesExplanation:Swapping S[0] and S[1] modifies S to "ABA" and B to "010".
15+ min read
Count of palindromic strings of size upto N consisting of first K alphabets occurring at most twice
Given two integers N and K, the task is to find the number of palindromic strings of size at most N consisting of the first K lowercase alphabets such that each character in a string doesn't appear more than twice. Examples: Input: N = 3, K = 2Output: 6Explanation:The possible strings are:"a", "b", "aa", "bb", "aba", "bab". Input: N = 4, K = 3Outpu
9 min read
Count of odd length contiguous Palindromic sequences in a Matrix
Given a matrix arr[][] of size MxN, the task is to find the number of contiguous palindromic sequences of odd length in that matrix. Example: Input: arr[][] = { { 2, 1, 2 }, { 1, 1, 1 }, { 2, 1, 2 }} Output: 15 Explanation Contiguous Palindromic sequences of odd length are: Row 1: (2), (1), (2), (2, 1, 2) =&gt; n(R1) = 4 Row 2: (1), (1), (1), (1, 1
11 min read
Count of N digit palindromic numbers divisible by 9
Given an integer N, the task is to count the number of N digit palindromic numbers containing digits from 1 to 9 and divisible by 9. Examples: Input: N = 1 Output: 1 Explanation: Only 9 is 1 digit number which is palindrome and divisible by 9.Input: N = 3 Output: 9 Explanation: Three digit numbers those are palindrome and divisible by 9 are - {171,
4 min read
Count of palindromic plus paths in a given Matrix
Given an N x M matrix of integers, the task is to count the number of palindromic pluses in the array. Palindromic plus is formed when a palindromic sub-row and palindromic sub-column cross each other at the middle element. Examples: Input: matrix = [[1, 2, 1], [2, 3, 2], [3, 2, 1]] Output: 1 Explanation: Palindromic row from (1, 0) - &gt; (1, 2) a
6 min read
Count of Palindromic Strings possible by swapping of a pair of Characters
Given a palindromic string S, the task is to find the count of palindromic strings possible by swapping a pair of character at a time.Examples: Input: s = "abba" Output: 2 Explanation: 1st Swap: abba -&gt; abba 2nd Swap: abba -&gt; abba All other swaps will lead to a non-palindromic string. Therefore, the count of possible strings is 2.Input: s = "
5 min read
Count N-length arrays made from first M natural numbers whose subarrays can be made palindromic by replacing less than half of its elements
Given two integer N and M, the task is to find the count of arrays of size N with elements from the range [1, M] in which all subarrays of length greater than 1 can be made palindromic by replacing less than half of its elements i.e., floor(length/2). Examples: Input: N = 2, M = 3Output: 6Explanation:There are 9 arrays possible of length 2 using va
4 min read
Maximize palindromic strings of length 3 possible from given count of alphabets
Given an array arr[] of size 26, representing frequencies of character 'a' to 'z', the task is to find the maximum number of palindromic strings of length 3 that can be generated from the specified count of alphabets. Examples: Input: arr[] = {4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}Output: 3Explanation:One of t
9 min read
Maximize count of 3-length palindromic subsequences with each index part of a single subsequence
Given a string, S, the task is to find the maximum number of distinct indexed palindromic subsequences of length 3 possible from the given string. Examples: Input: str = “geekforg”Output: 2Explanation:Possible palindromic subsequences of length 3 satisfying the conditions are "gkg" and "efe". Therefore, the required output is 2. Input: str = "geek"
6 min read
Count of palindromic rows in given Matrix
Given a matrix arr[][] of size N * N, the task is to find the number of palindromic rows. Examples: Input: arr[][] = {{1, 3, 1}, {2, 2, 3}, {2, 1, 2}} Output: 2Explanation: First and third row forms a palindrome i.e 1 3 1 and 2 1 2. Therefore, count of palindromic rows is 2. Input: arr[][] = {{2, 2, 3, 2}, {1, 3, 3, 1}, {4, 2, 2, 4}, {5, 6, 6, 5}}
4 min read
Article Tags :
Practice Tags :