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 DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example 12 min read Like