Related Articles

# Number of alternating substrings from a given Binary String

• Last Updated : 03 Aug, 2021

Given a binary string of size N, the task is to count the number of alternating substrings that are present in the string S.

Examples:

Input: S = “0010”
Output: 7
Explanation:
All the substring of the string S are: {“0”, “00”, “001”, “0010”, “0”, “01”, “010”, “1”, “10”, “0”}
Strings that are alternating: {“0”, “0”, “01”, “010”, “1”, “10”, “0”}.

Input: S = “010”
Output: 6

Naive Approach: The simplest approach to solve this problem is to first, find all the substrings of the string S, then check for every string if it is alternating or not.

Time Complexity: O(N3)
Auxiliary Space: O(N2)

Efficient Approach: This problem has Overlapping Subproblems property and Optimal Substructure property. So this problem can be solved using Dynamic Programming. Follow the steps below to solve this problem:

• Declare a dp array, where dp[i][j] stores the number of alternating strings that start with char i and are in the range [j, N-1].
• Iterate in the range [N-1, 0] using the variable i and perform the following steps:
• If i is equal to N-1, then if current character is ‘1’, then assign 1 to dp[i], otherwise assign 1 to dp[i].
• Else, if current character is ‘0’, then update dp[i] to 1+dp[i+1], otherwise, update dp[i] to 1+dp[i+1].
• Initialize a variable say ans as 0 to store the number of substrings that are alternating.
• Iterate in the range [0, N-1] using the variable i and perform the following steps:
• Update ans as max of dp[i] and dp[i].
• Finally, print the value obtained in ans as the answer.

Below is the implementation of the above approach:

## C++

 `// c++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to count number of alternating``// substrings from a given binary string``int` `countAlternatingSubstrings(string S, ``int` `N)``{``    ``// Initialize dp array, where dp[i][j] stores``    ``// the number of alternating strings starts``    ``// with i and having j elements.``    ``vector > dp(2, vector<``int``>(N, 0));` `    ``// Traverse the string from the end``    ``for` `(``int` `i = N - 1; i >= 0; i--) {` `        ``// If i is equal to N - 1``        ``if` `(i == N - 1) {` `            ``if` `(S[i] == ``'1'``)``                ``dp[i] = 1;` `            ``else``                ``dp[i] = 1;``        ``}``        ``// Otherwise,``        ``else` `{` `            ``// Increment count of``            ``// substrings starting at i``            ``// and has 0 in the beginning``            ``if` `(S[i] == ``'0'``)``                ``dp[i] = 1 + dp[i + 1];` `            ``// Increment count of``            ``// substrings starting at i``            ``// and has 1 in the beginning``            ``else``                ``dp[i] = 1 + dp[i + 1];``        ``}``    ``}``    ``// Stores the result``    ``int` `ans = 0;` `    ``// Iterate in the range [0, N-1]``    ``for` `(``int` `i = 0; i < N; i++) {` `        ``// Update ans``        ``ans += max(dp[i], dp[i]);``    ``}` `    ``// Return the ans``    ``return` `ans;``}` `// Driver code``int` `main()``{``    ``// Given Input``    ``string S = ``"0010"``;``    ``int` `N = S.length();` `    ``// Function call``    ``cout << countAlternatingSubstrings(S, N);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;` `class` `GFG{` `// Function to count number of alternating``// substrings from a given binary string``static` `int` `countAlternatingSubstrings(String S, ``int` `N)``{``    ` `    ``// Initialize dp array, where dp[i][j] stores``    ``// the number of alternating strings starts``    ``// with i and having j elements.``    ``int``[][] dp = ``new` `int``[``2``][N];``    ``for``(``int` `i = ``0``; i < ``2``; i++)``    ``{``        ``for``(``int` `j = ``0``; j < N; j++)``        ``{``            ``dp[i][j] = ``0``;``        ``}``    ``}` `    ``// Traverse the string from the end``    ``for``(``int` `i = N - ``1``; i >= ``0``; i--)``    ``{``        ` `        ``// If i is equal to N - 1``        ``if` `(i == N - ``1``)``        ``{``            ``if` `(S.charAt(i) == ``'1'``)``                ``dp[``1``][i] = ``1``;` `            ``else``                ``dp[``0``][i] = ``1``;``        ``}``        ` `        ``// Otherwise,``        ``else``        ``{``            ` `            ``// Increment count of``            ``// substrings starting at i``            ``// and has 0 in the beginning``            ``if` `(S.charAt(i) == ``'0'``)``                ``dp[``0``][i] = ``1` `+ dp[``1``][i + ``1``];` `            ``// Increment count of``            ``// substrings starting at i``            ``// and has 1 in the beginning``            ``else``                ``dp[``1``][i] = ``1` `+ dp[``0``][i + ``1``];``        ``}``    ``}``    ` `    ``// Stores the result``    ``int` `ans = ``0``;` `    ``// Iterate in the range [0, N-1]``    ``for``(``int` `i = ``0``; i < N; i++)``    ``{``        ` `        ``// Update ans``        ``ans += Math.max(dp[``0``][i], dp[``1``][i]);``    ``}` `    ``// Return the ans``    ``return` `ans;``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ` `    ``// Given Input``    ``String S = ``"0010"``;``    ``int` `N = S.length();``    ` `    ``// Function call``    ``System.out.print(countAlternatingSubstrings(S, N));``}``}` `// This code is contributed by sanjoy_62`

## Python3

 `# Python3 program for the above approach` `# Function to count number of alternating``# substrings from a given binary string``def` `countAlternatingSubstrings(S, N):``    ` `    ``# Initialize dp array, where dp[i][j] stores``    ``# the number of alternating strings starts``    ``# with i and having j elements.``    ``dp ``=` `[[``0` `for` `i ``in` `range``(N)]``             ``for` `i ``in` `range``(``2``)]` `    ``# Traverse the string from the end``    ``for` `i ``in` `range``(N ``-` `1``, ``-``1``, ``-``1``):``        ` `        ``# If i is equal to N - 1``        ``if` `(i ``=``=` `N ``-` `1``):` `            ``if` `(S[i] ``=``=` `'1'``):``                ``dp[``1``][i] ``=` `1``            ``else``:``                ``dp[``0``][i] ``=` `1``                ` `        ``# Otherwise,``        ``else``:` `            ``# Increment count of``            ``# substrings starting at i``            ``# and has 0 in the beginning``            ``if` `(S[i] ``=``=` `'0'``):``                ``dp[``0``][i] ``=` `1` `+` `dp[``1``][i ``+` `1``]` `            ``# Increment count of``            ``# substrings starting at i``            ``# and has 1 in the beginning``            ``else``:``                ``dp[``1``][i] ``=` `1` `+` `dp[``0``][i ``+` `1``]``                ` `    ``# Stores the result``    ``ans ``=` `0` `    ``# Iterate in the range [0, N-1]``    ``for` `i ``in` `range``(N):``        ` `        ``# Update ans``        ``ans ``+``=` `max``(dp[``0``][i], dp[``1``][i])` `    ``# Return the ans``    ``return` `ans` `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``# Given Input``    ``S ``=` `"0010"``    ``N ``=` `len``(S)` `    ``# Function call``    ``print` `(countAlternatingSubstrings(S, N))` `# This code is contributed by mohit kumar 29`

## C#

 `// C# program for the above approach``using` `System;` `class` `GFG{` `// Function to count number of alternating``// substrings from a given binary string``static` `int` `countAlternatingSubstrings(``string` `S, ``int` `N)``{``    ` `    ``// Initialize dp array, where dp[i][j] stores``    ``// the number of alternating strings starts``    ``// with i and having j elements.``    ``int``[,] dp = ``new` `int``[2, N];``    ``for``(``int` `i = 0; i < 2; i++)``    ``{``        ``for``(``int` `j = 0; j < N; j++)``        ``{``            ``dp[i, j] = 0;``        ``}``    ``}` `    ``// Traverse the string from the end``    ``for``(``int` `i = N - 1; i >= 0; i--)``    ``{``        ` `        ``// If i is equal to N - 1``        ``if` `(i == N - 1)``        ``{``            ``if` `(S[i] == ``'1'``)``                ``dp[1, i] = 1;` `            ``else``                ``dp[0, i] = 1;``        ``}``        ` `        ``// Otherwise,``        ``else``        ``{``            ` `            ``// Increment count of``            ``// substrings starting at i``            ``// and has 0 in the beginning``            ``if` `(S[i] == ``'0'``)``                ``dp[0, i] = 1 + dp[1, i + 1];` `            ``// Increment count of``            ``// substrings starting at i``            ``// and has 1 in the beginning``            ``else``                ``dp[1, i] = 1 + dp[0, i + 1];``        ``}``    ``}``    ` `    ``// Stores the result``    ``int` `ans = 0;` `    ``// Iterate in the range [0, N-1]``    ``for``(``int` `i = 0; i < N; i++)``    ``{``        ` `        ``// Update ans``        ``ans += Math.Max(dp[0, i], dp[1, i]);``    ``}` `    ``// Return the ans``    ``return` `ans;``}` `// Driver Code``public` `static` `void` `Main()``{``  ` `    ``// Given Input``    ``string` `S = ``"0010"``;``    ``int` `N = S.Length;``    ` `    ``// Function call``    ``Console.Write(countAlternatingSubstrings(S, N));``}``}` `// This code is contributed by target_2.`

## Javascript

 ``
Output:
`7`

Time Complexity: O(N)
Auxiliary Space: O(N) My Personal Notes arrow_drop_up