Write a program in C++ to count the Number of substrings that starts with β€˜1’ and ends with β€˜1’


Let’s suppose we have given a length of string ‘str’ and a string. The task is to count the number of substrings that starts with ‘1’ and ends with ‘1’ in a given Binary String. A Binary String contains ‘1’ and ‘0’ only. For example,

Input-1

N = 5
str = ‘11101’

Output

6

Explanation − In the given Binary String, we have 6 substrings that starts with ‘1’ and ends with ‘1’. The set of these substrings are {‘11’, ‘111’, ‘1110’, ‘11101’, ‘1101’, ‘101’}.

Input-1

N = 4
str = ‘0011’

Output

1

Explanation

In the given Binary String we have 1 substring that starts with ‘1’ and ends with ‘1’. The set of these substrings is a singleton set i.e., { ‘11 ’}.

The approach used to solve this problem

For the given string, we have to count the number of substrings that start with ‘1’ and end with ‘1’. The problem is similar to the well-known Handshake problem in which we have to count the number of handshakes in a party of ‘n’ people.

If we count the number of 1’s in the given string, then we can find the set of substrings that starts with ‘1’ and ends with ‘1’.

  • Take Input a string of N length.

  • An Integer function countSubstring(int N, string s) takes the length of the string and a string as input and returns the count of all the substring that starts with ‘1’ and ends with ‘1’.

  • Iterate over the whole string and count the no. of ‘1’ in the string.

  • Count the no. of substring (pair) in the given string by n*(n-1)/2.

  • Return the result of n*(n-1)/2.

Example

 Live Demo

#include<iostream>
using namespace std;
int countSubstring(int N, string s){
   int count=0;
   for(int i=0; s[i]!= '\0'; ++i){
      if( s[i]== '1' )
         count++;
   }
   return count*(count-1)/2;
}
int main() {
   int N=5;
   string str= "11101";
   cout<< countSubstring(N,str)<<endl;
   return 0;
}

Output

If we will run the above code then it will print the output as,

6

Since the number of ‘1’s present in the given string is ‘4’ i.e., count = 4, the total number of the substring that starts with ‘1’ and ends with ‘1’ are, 4*(4-1)/2 = 6.

Updated on: 05-Feb-2021

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements