Count Substrings that can be made of length 1 by replacing “01” or “10” with 1 or 0
Last Updated :
16 Aug, 2022
Given a binary string S of length N, the task is to find the number of pairs of integers [L, R] 1 ≤ L < R ≤ N such that S[L . . . R] (the substring of S from L to R) can be reduced to 1 length string by replacing substrings “01” or “10” with “1” and “0” respectively.
Examples:
Input: S = “0110”
Output: 4
Explanation: The 4 substrings are 01, 10, 110, 0110.
Input: S = “00000”
Output: 0
Approach: The solution is based on the following mathematical idea:
We can solve this based on the exclusion principle. Instead of finding possible pairs find the number of impossible cases and subtract that from all possible substrings (i.e. N*(N+1)/2 ).
How to find impossible cases?
When s[i] and s[i-1] are same, then after reduction it will either become “00” or “11”. In both cases, the substring cannot be reduced to length 1. So substring from 0 to i, from 1 to i, . . . cannot be made to have length 1. That count of substrings is i.
Follow the below steps to solve the problem:
- Initialize answer ans = N * (N + 1) / 2
- Run a loop from i = 1 to N – 1
- If S[i] is equal to S[i – 1], then subtract i from ans.
- Return ans – N (because there are N substrings having length 1).
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll find(string Str)
{
ll n = Str.size();
ll ans = n * (n + 1) / 2;
for (ll i = 1; i < n; i++) {
if (Str[i] == Str[i - 1])
ans -= i;
}
return ans - n;
}
int main()
{
string S = "0110" ;
cout << find(S) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static long find(String Str)
{
int n = Str.length();
long ans = n * (n + 1 ) / 2 ;
for ( int i = 1 ; i < n; i++) {
if (Str.charAt(i) == Str.charAt(i - 1 ))
ans -= i;
}
return ans - n;
}
public static void main(String[] args)
{
String S = "0110" ;
System.out.println(find(S));
}
}
|
Python3
def find( Str ):
n = len ( Str )
ans = n * (n + 1 ) / 2
for i in range ( 0 , n):
if ( Str [i] = = Str [i - 1 ]):
ans - = i;
return ans - n
if __name__ = = "__main__" :
S = "0110"
print ( int (find(S)));
|
C#
using System;
public class GFG {
public static long find(String Str)
{
int n = Str.Length;
long ans = n * (n + 1) / 2;
for ( int i = 1; i < n; i++) {
if (Str[i] == Str[i - 1])
ans -= i;
}
return ans - n;
}
static public void Main()
{
String S = "0110" ;
Console.WriteLine(find(S));
}
}
|
Javascript
<script>
function find(Str)
{
let n = Str.length;
let ans = n * (n + 1) / 2;
for (let i = 1; i < n; i++) {
if (Str[i] == Str[i - 1])
ans -= i;
}
return ans - n;
}
let S = "0110" ;
document.write(find(S));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...