VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-palindromic-substrings-in-a-binary-string/

⇱ Count Palindromic Substrings in a Binary String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Palindromic Substrings in a Binary String

Last Updated : 23 Jul, 2025

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: 4
Explanation: "0", "1", "1" and "11" are the palindromic substrings.

Input: S = "0"
Output: 1
Explanation: "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:


Output
10

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment