Count Palindromic Substrings in a Binary String Last Updated : 11 Nov, 2023 Comments Improve Suggest changes Like Article Like Report 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: This can be solved with the following idea: Using some mathematical observation can find out number of possible palindrome substring of size 2. Rest of all size, we can find out by reducing indexes from left and right side. For more clarification, see steps. Below are the steps to solve the problem: Iterate in for loop from 0 to N - 1.Checking whether adjacent characters are equal or not and adding in the count.Again iterate in the loop, and look for the following conditions:Start reducing the index from left and if s[i - 1]== '0', we can decrement l by 1.After that, iterate from right and if s[i + 1] == '0', we can increment r by 1.Update ans += min(abs(l - i), abs(r - i)).And if S[ i - 1] == '1', we can increment total count of palindrome by 1. Below is the implementation of the code: C++ // C++ code for the above approach: #include <bits/stdc++.h> #include <iostream> using namespace std; // Function to count number of plaindrome long long countPalindrome(string S) { // Size of string int N = S.size(); long long ans = 0, x = 0; for (int i = 0; i < N; i++) { x++; // If adjacent character are same if (i + 1 < N && S[i] == S[i + 1]) continue; // Count total number of possibility ans += (x * (x + 1)) / 2; x = 0; } int last = -1; for (int i = 0; i < N; i++) { if (S[i] == '1') { int l = i; int r = i; // Start iterating from right side while (l - 1 >= 0 && S[l - 1] == '0') l--; // Start iterating from left side while (r + 1 < N && S[r + 1] == '0') r++; ans += min(abs(l - i), abs(r - i)); if (last == -1) { last = i; } else { // Add the min value ans += min(last, N - i - 1); if (S[i - 1] != '1') { ans++; } } } } // Return the total count of // palindromic substrings return ans; } // Driver code int main() { string s = "01110"; // Function call cout << countPalindrome(s); return 0; } Java // Code contributed by Flutterfly import java.util.*; class Main { public static long countPalindrome(String S) { // Size of string int N = S.length(); long ans = 0, x = 0; for (int i = 0; i < N; i++) { x++; // If adjacent character are same if (i + 1 < N && S.charAt(i) == S.charAt(i + 1)) continue; // Count total number of possibility ans += (x * (x + 1)) / 2; x = 0; } int last = -1; for (int i = 0; i < N; i++) { if (S.charAt(i) == '1') { int l = i; int r = i; // Start iterating from right side while (l - 1 >= 0 && S.charAt(l - 1) == '0') l--; // Start iterating from left side while (r + 1 < N && S.charAt(r + 1) == '0') r++; ans += Math.min(Math.abs(l - i), Math.abs(r - i)); if (last == -1) { last = i; } else { // Add the min value ans += Math.min(last, N - i - 1); if (S.charAt(i - 1) != '1') { ans++; } } } } // Return the total count of // palindromic substrings return ans; } // Driver code public static void main(String[] args) { String s = "01110"; //Function call System.out.println(countPalindrome(s)); } } Python # code contributed by Flutterfly # Function to count number of palindrome def countPalindrome(S): #Size of string N = len(S) ans = 0 x = 0 for i in range(N): x += 1 #If adjacent character are same if i + 1 < N and S[i] == S[i + 1]: continue #Count total number of possibility ans += (x * (x + 1)) // 2 x = 0 last = -1 for i in range(N): if S[i] == '1': l = i r = i #Start iterating from right side while l - 1 >= 0 and S[l - 1] == '0': l -= 1 #Start iterating from left side while r + 1 < N and S[r + 1] == '0': r += 1 ans += min(abs(l - i), abs(r - i)) if last == -1: last = i else: #Add the min value ans += min(last, N - i - 1) if S[i - 1] != '1': ans += 1 #Return the total count of palindromic substrings return ans #Driver code s = "01110" #Function call print(countPalindrome(s)) C# // Code contributed by Flutterfly using System; public class Program { // Function to count number of plaindrome public static long CountPalindrome(string S) { // Size of string int N = S.Length; long ans = 0, x = 0; for (int i = 0; i < N; i++) { x++; // If adjacent character are same if (i + 1 < N && S[i] == S[i + 1]) continue; // Count total number of possibility ans += (x * (x + 1)) / 2; x = 0; } int last = -1; for (int i = 0; i < N; i++) { if (S[i] == '1') { int l = i; int r = i; // Start iterating from right side while (l - 1 >= 0 && S[l - 1] == '0') l--; // Start iterating from left side while (r + 1 < N && S[r + 1] == '0') r++; ans += Math.Min(Math.Abs(l - i), Math.Abs(r - i)); if (last == -1) { last = i; } else { // Add the min value ans += Math.Min(last, N - i - 1); if (S[i - 1] != '1') { ans++; } } } } // Return the total count of // palindromic substrings return ans; } //Driver code public static void Main() { string s = "01110"; // Function call Console.WriteLine(CountPalindrome(s)); } } JavaScript // JavaScript code for the above approach: // Function to count number of plaindrome function countPalindrome(S) { // Size of string const N = S.length; let ans = 0; let x = 0; for (let i = 0; i < N; i++) { x++; // If adjacent character are same if (i + 1 < N && S[i] === S[i + 1]) continue; // Count total number of possibility ans += (x * (x + 1)) / 2; x = 0; } let last = -1; for (let i = 0; i < N; i++) { if (S[i] === '1') { let l = i; let r = i; // Start iterating from right side while (l - 1 >= 0 && S[l - 1] === '0') l--; // Start iterating from left side while (r + 1 < N && S[r + 1] === '0') r++; ans += Math.min(Math.abs(l - i), Math.abs(r - i)); if (last === -1) { last = i; } else { // Add the min value ans += Math.min(last, N - i - 1); if (S[i - 1] !== '1') { ans++; } } } } // Return the total count of // palindromic substrings return ans; } // Driver code const S = "01110"; // Function call console.log(countPalindrome(S)); Output10Time Complexity: O(N)Auxiliary Space: O(1) Comment More infoAdvertise with us Next Article Count Palindromic Substrings in a Binary String S suru21 Follow Improve Article Tags : Strings Geeks Premier League DSA palindrome Geeks Premier League 2023 +1 More Practice Tags : palindromeStrings Similar Reads Count of Palindromic substrings in an Index range Given a string str of small alphabetic characters other than this we will be given many substrings of this string in form of index tuples. We need to find out the count of the palindromic substrings in given substring range. Examples: Input : String str = "xyaabax" Range1 = (3, 5) Range2 = (2, 3) Ou 11 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 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 subsequenc 15+ min read Counting even decimal value substrings in a binary string Given a binary string of size N. Count all substring that have even decimal value considering binary to decimal conversion from left to right (For example a substring "1011" is treated as 13) Examples : Input : 101Output : 2Explanation : Substring are : 1, 10, 101, 0, 01, 1 In decimal form : 1, 1, 3 9 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 t 9 min read Count of Reverse Bitonic Substrings in a given String Given a string S, the task is to count the number of Reverse Bitonic Substrings in the given string. Reverse bitonic substring: A string in which the ASCII values of the characters of the string follow any of the following patterns: Strictly IncreasingStrictly decreasingDecreasing and then increasin 8 min read Count special palindromes in a String 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 substring 11 min read Generate a String of having N*N distinct non-palindromic Substrings Given an even integer N, the task is to construct a string such that the total number of distinct substrings of that string that are not a palindrome equals N2. Examples: Input: N = 2 Output: aabb Explanation: All the distinct non-palindromic substrings are ab, abb, aab and aabb. Therefore, the coun 3 min read Count of substrings of a binary string containing K ones Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones. Examples: Input : s = â10010â K = 1 Output : 9 The 9 substrings containing one 1 are, â1â, â10â, â100â, â001â, â01â, â1â, â10â, â0010â and â010âRecommen 7 min read Palindrome Substrings Count using Center Expansion Given a string, the task is to find the count of all the palindromic substrings in a given string with a length greater than or equal to 2.Examples:Input: s = "abaab"Output: 3Explanation: Palindrome substrings (of length > 1) are "aba" , "aa" , "baab" Input : s = "aaa"Output: 3Explanation : Palin 6 min read Like