Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 substrings of a given string whose anagram is a palindrome
Next article icon

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
Count substrings of a given string whose anagram is a palindrome
author
harshverma28
Improve
Article Tags :
  • Strings
  • DSA
  • strings
Practice Tags :
  • Strings
  • Strings

Similar Reads

  • Count All Palindromic Subsequence in a given String
    Given a string s of length n, the task is to count number of palindromic subsequence (need not necessarily be distinct) present in the string s. Example: Input: s = "abcd"Output: 4Explanation: Palindromic subsequence are : "a" ,"b", "c" ,"d" Input: s = "aab"Output: 4Explanation: palindromic subseque
    15+ min read
  • Count substrings of a given string whose anagram is a palindrome
    Given a string S of length N containing only lowercase alphabets, the task is to print the count of substrings of the given string whose anagram is palindromic. Examples: Input: S = "aaaa"Output: 10Explanation:Possible substrings are {"a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"}. Sinc
    10 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
  • Check if K palindromic strings can be formed from a given string
    Given a string S of size N and an integer K, the task is to find whether the characters of the string can be arranged to make K palindromic strings simultaneously. Examples: Input: S = "annabelle", K = 2 Output: Yes Explanation: All characters of string S can be distributed into "elble" and "anna" w
    7 min read
  • Find all Palindrome Strings in given Array of strings
    Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to find all palindromic string in the array. Print -1 if no palindrome is present in the given array. Examples: Input: arr[] = {"abc", "car", "ada", "racecar", "cool"}Output: "ada", "ra
    6 min read
  • Count of substrings of a given Binary string with all characters same
    Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = “011”Output: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
    10 min read
  • Rearrange characters of a string to make it a concatenation of palindromic substrings
    Given a string S consisting of lowercase alphabets, the task is to check whether the given string can be rearranged such that the string can be split into non-overlapping palindromic substrings of at least length 2. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "
    6 min read
  • Count of substrings of given string with frequency of each character at most K
    Given a string str, the task is to calculate the number of substrings of the given string such that the frequency of each element of the string is almost K. Examples: Input: str = "abab", K = 1Output: 7Explanation: The substrings such that the frequency of each character is atmost 1 are "a", "b", "a
    6 min read
  • Count strings from given array having all characters appearing in a given string
    Given an array of strings arr[][] of size N and a string S, the task is to find the number of strings from the array having all its characters appearing in the string S. Examples: Input: arr[][] = {"ab", "aab", "abaaaa", "bbd"}, S = "ab"Output: 3Explanation: String "ab" have all the characters occur
    6 min read
  • All distinct palindromic sub-strings of a given string
    Given a string str of lowercase ASCII characters. The task is to find all the distinct continuous palindromic sub-strings which are present in the string str. Examples: Input: str = "abaaa"Output: [ "a", "aa", "aaa", "aba", "b" ]Explanation: All 5 distinct continuous palindromic sub-strings are list
    15+ 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