Open In App

Count all palindromic Substrings for each character in a given String

Last Updated : 05 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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", K = 2
Output : A[] = [1 1 2 2 1 1 2]
Explanation: A[0] = 1 => removing char s[0] = 'a' only one palindromic substring of length 2 is possible i.e. "bb"
A[1] = 1 => removing char s[1] = 'a' only one palindromic substring of length 2 is possible i.e. "bb" 
A[2] = 2 => removing char s[2] = 'b' two palindromic substring of length 2 are possible i.e. "aa" and "bb"
A[3] = 2 => removing char s[3] = 'a' two palindromic substring of length 2 are possible i.e. "aa" and "bb" 
A[4] = 1 => removing char s[4] = 'b' only one palindromic substring of length 2 is possible i.e. "aa" 
A[5] = 1 => removing char s[5] = 'b' only one palindromic substring of length 2 is possible i.e. "aa" 
A[6] = 2 => removing char s[6] = 'a' two palindromic substring of length 2 are possible i.e. "aa" and "bb" 

Input: S = "abbab", K = 2
Output: A[] = [1 0 0 1 1]
Explanation: A[0] = 1 => removing char s[0] = 'a' only one palindromic substring of length 2 is possible i.e. "bb"
A[1] = 1 => removing char s[1] = 'b' no palindromic substring of length 2 is possible
A[2] = 2 => removing char s[2] = 'b' no palindromic substring of length 2 is possible
A[3] = 2 => removing char s[3] = 'a' only one palindromic substring of length 2 is possible i.e. "bb"
A[4] = 1 => removing char s[4] = 'b' only one palindromic substring of length 2 is possible i.e. "bb"

Approach: To solve the problem follow the below steps:

  • For character S[i] of the string, we need to find palindromic substrings of length K such that the substrings don't include S[i]. This approach requires one loop to iterate the string and two separate inner for loops because we don't have to include the character S[i] so we need to skip the entire range for which S[i] is included in any substring.
  • Run a loop to iterate the string from i = 0 to i < length of string. 
  • The first inner loop will run from j = 0 to j ? i - K, then the last substring before S[i] will start from i - K and end at i - 1 which won't include S[i].
  • The second inner loop starts from j = i + 1 to n - 1.
  • For each substring, check if it is a palindrome, then increment the counter for that character S[i].

Below are the steps for the above approach:

  • Create an array A[] to store the count of the number of palindromic substrings for S[i].
  • Run a loop to iterate the string from i = 0 to i < S.length.
  • Initialize a counter-variable count = 0.
  • The first inner loop runs from j = 0 to j = i - K and generates a substring from j of length K to check if it is a palindrome, incrementing the counter.
  • The second inner loop runs from j = i+1 to j = l - 1 and generates a substring from j of length k to check if it is a palindrome, and increment the counter.
  • When both inner loop ends, update A[i] = count
  • Return the array A[].

Below is the implementation for the above approach:

C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;

// function to check if a string is palindrome
bool isPalin(string s, int l)
{
    for (int i = 0; i < l; i++) {
        if (s[i] != s[l - i - 1])
            return false;
    }
    return true;
}

// function to count the number of palindromic
// substrings for each character of a string
void findCount(string s, int l, int k, int A[])
{
    for (int i = 0; i < s.length(); i++) {
        int count = 0;

        // loop 1
        for (int j = 0; j <= i - k; j++) {
            string sub = s.substr(j, k);
            if (isPalin(sub, k))
                count++;
        }

        // loop 2
        for (int j = i + 1; j < l; j++) {
            string sub = s.substr(j, k);
            if (isPalin(sub, k))
                count++;
        }

        A[i] = count;
    }
}

// Driver function
int main()
{
    string s = "aababba"; // given string
    int l = 7; // length of string
    int k = 2; // length of substring

    // array to store the count
    int A[s.length()];

    // function call
    findCount(s, l, k, A);

    cout << "Count of palindromic substrings for "
         << "each character of string s is: [ ";
    for (int i = 0; i < s.length(); i++)
        cout << A[i] << " ";
    cout << "]" << '\n';
}
Java
// Java code implementation

import java.io.*;

class Main {

    // function to check if a string is palindrome
    static boolean isPalin(String s, int l)
    {
        for (int i = 0; i < l; i++) {
            if (s.charAt(i) != s.charAt(l - i - 1))
                return false;
        }
        return true;
    }

    // function to count the number of palindromic
    // substrings for each character of a string
    static void findCount(String s, int l, int k, int[] A)
    {
        for (int i = 0; i < s.length(); i++) {
            int count = 0;

            // loop 1
            for (int j = 0; j <= i - k; j++) {
                if (j + k <= s.length()) {
                    String sub = s.substring(j, j + k);
                    if (isPalin(sub, k))
                        count++;
                }
            }

            // loop 2
            for (int j = i + 1; j < l; j++) {
                if (j + k <= s.length()) {
                    String sub = s.substring(j, j + k);
                    if (isPalin(sub, k))
                        count++;
                }
            }

            A[i] = count;
        }
    }

    public static void main(String[] args)
    {
        String s = "aababba"; // given string
        int l = 7; // length of string
        int k = 2; // length of substring

        // array to store the count
        int[] A = new int[s.length()];

        // function call
        findCount(s, l, k, A);

        System.out.print(
            "Count of palindromic substrings for each character of string s is: [ ");
        for (int i = 0; i < s.length(); i++)
            System.out.print(A[i] + " ");
        System.out.println("]");
    }
}

// This code is contributed by karthik.
Python3
# Python code implementation for the above program

# Function to check if a string is palindrome
def is_palindrome(s, l):
    for i in range(l):
        if s[i] != s[l - i - 1]:
            return False
    return True

# Function to count the number of palindromic
# substrings for each character of a string
def find_count(s, l, k):
    A = [0] * len(s)
    for i in range(len(s)):
        count = 0

        # loop 1
        for j in range(i - k + 1):
            if j + k <= len(s):
                sub = s[j:j + k]
                if is_palindrome(sub, k):
                    count += 1

        # loop 2
        for j in range(i + 1, l):
            if j + k <= len(s):
                sub = s[j:j + k]
                if is_palindrome(sub, k):
                    count += 1

        A[i] = count

    return A


s = "aababba"  # given string
l = 7  # length of string
k = 2  # length of substring

# Function call
A = find_count(s, l, k)

print("Count of palindromic substrings for each character of string s is: ", A)

# This code is contributed by sankar.
C#
// C# code implementation
using System;

namespace PalindromicSubstrings
{
  class Program
  {
    // function to check if a string is palindrome
    static bool IsPalin(string s, int l)
    {
      for (int i = 0; i < l; i++)
      {
        if (s[i] != s[l - i - 1])
          return false;
      }
      return true;
    }

    // function to count the number of palindromic
    // substrings for each character of a string
    static void FindCount(string s, int l, int k, int[] A)
    {
      for (int i = 0; i < s.Length; i++)
      {
        int count = 0;

        // loop 1
        for (int j = 0; j <= i - k; j++)
        {
          if (j + k <= s.Length)
          {
            string sub = s.Substring(j, k);
            if (IsPalin(sub, k))
              count++;
          }
        }

        // loop 2
        for (int j = i + 1; j < l; j++)
        {
          if (j + k <= s.Length)
          {
            string sub = s.Substring(j, k);
            if (IsPalin(sub, k))
              count++;
          }
        }

        A[i] = count;
      }
    }

    static void Main(string[] args)
    {
      string s = "aababba"; // given string
      int l = 7; // length of string
      int k = 2; // length of substring

      // array to store the count
      int[] A = new int[s.Length];

      // function call
      FindCount(s, l, k, A);

      Console.Write("Count of palindromic substrings for each character of string s is: [ ");
      for (int i = 0; i < s.Length; i++)
        Console.Write($"{A[i]} ");
      Console.WriteLine("]");
    }
  }
}
JavaScript
<script>
    // JavaScript program for the above approach
    
    // function to check if a string is palindrome
    function isPalin(s, l) {
      for (let i = 0; i < l; i++) {
    if (s.charAt(i) !== s.charAt(l - i - 1)) {
      return false;
    }
      }
      return true;
    }
    
    // function to count the number of palindromic
    // substrings for each character of a string
    function findCount(s, l, k) {
      const A = []; // array to store the count
      for (let i = 0; i < s.length; i++) {
    let count = 0;
    
    // loop 1
    for (let j = 0; j <= i - k; j++) {
      if (j + k <= s.length) {
        const sub = s.substring(j, j + k);
        if (isPalin(sub, k)) {
          count++;
        }
      }
    }
    
    // loop 2
    for (let j = i + 1; j < l; j++) {
      if (j + k <= s.length) {
        const sub = s.substring(j, j + k);
        if (isPalin(sub, k)) {
          count++;
        }
      }
    }
    
    A[i] = count;
      }
      return A;
    }
    
    // main function
    function main() {
      const s = 'aababba'; // given string
      const l = 7; // length of string
      const k = 2; // length of substring
    
      // function call
      const A = findCount(s, l, k);
    
      console.log(`Count of palindromic substrings for
      each character of string s is: [ ${A.join(' ')} ]`);
    }
    
    // calling main function
    main();
    
    // This code is contributed by Susobhan Akhuli
</script>

Output
Count of palindromic substrings for each character of string s is: [ 1 1 2 2 1 1 2 ]

Time Complexity: O(l2) where l is the length of the string
Auxiliary Space: O(l) where l is the length of the Resultant Array


Next Article
Article Tags :
Practice Tags :

Similar Reads