Given a binary string, count number of substrings that start and end with 1. - GeeksforGeeks

28 Apr, 2021
Given a binary string, count number of substrings that start and end with 1. For example, if the input string is “00100101”, then there are three substrings “1001”, “100101” and “101”.Source: Amazon Interview Experience | Set 162Difficulty Level: Rookie 
A Simple Solution is to run two loops. Outer loops picks every 1 as starting point and inner loop searches for ending 1 and increments count whenever it finds 1. 
C++
Java
Python3
C#
PHP
Javascript
// A simple C++ program to count number of// substrings starting and ending with 1#include<iostream>  using namespace std; int countSubStr(char str[]){int res = 0; // Initialize result // Pick a starting pointfor (int i=0; str[i] !='\0'; i++){        if (str[i] == '1')        {            // Search for all possible ending point            for (int j=i+1; str[j] !='\0'; j++)            if (str[j] == '1')                res++;        }}return res;} // Driver program to test above functionint main(){char str[] = "00100101";cout << countSubStr(str);return 0;}
// A simple C++ program to count number of//substrings starting and ending with 1 class CountSubString{    int countSubStr(char str[],int n)    {        int res = 0;  // Initialize result         // Pick a starting point        for (int i = 0; i<n; i++)        {            if (str[i] == '1')            {                // Search for all possible ending point                for (int j = i + 1; j< n; j++)                {                    if (str[j] == '1')                        res++;                }            }        }        return res;    }     // Driver program to test the above function    public static void main(String[] args)    {        CountSubString count = new CountSubString();        String string = "00100101";        char str[] = string.toCharArray();        int n = str.length;        System.out.println(count.countSubStr(str,n));    }}
# A simple Python 3 program to count number of# substrings starting and ending with 1 def countSubStr(st, n) :         # Initialize result    res = 0       # Pick a starting point    for i in range(0, n) :        if (st[i] == '1') :             # Search for all possible ending point            for j in range(i+1, n) :                if (st[j] == '1') :                    res = res + 1             return res       # Driver program to test above functionst = "00100101";list(st)n= len(st)print(countSubStr(st, n), end="")  # This code is contributed# by Nikita Tiwari.
// A simple C# program to count number of// substrings starting and ending with 1using System; class GFG{public virtual int countSubStr(char[] str,                               int n){    int res = 0; // Initialize result     // Pick a starting point    for (int i = 0; i < n; i++)    {        if (str[i] == '1')        {            // Search for all possible            // ending point            for (int j = i + 1; j < n; j++)            {                if (str[j] == '1')                {                    res++;                }            }        }    }    return res;} // Driver Codepublic static void Main(string[] args){    GFG count = new GFG();    string s = "00100101";    char[] str = s.ToCharArray();    int n = str.Length;    Console.WriteLine(count.countSubStr(str,n));}} // This code is contributed by Shrikant13
<?php// A simple PHP program to count number of// substrings starting and ending with 1 function countSubStr($str){    $res = 0; // Initialize result     // Pick a starting point    for ($i = 0; $i < strlen($str); $i++)    {            if ($str[$i] == '1')            {                // Search for all possible                // ending point                for ($j = $i + 1;                     $j < strlen($str); $j++)                if ($str[$j] == '1')                    $res++;            }    }    return $res;} // Driver Code$str = "00100101";echo countSubStr($str); // This code is contributed by ita_c?>
<script> // A simple javascript program to count number of// substrings starting and ending with 1         function countSubStr(str,n)    {        let res = 0;  // Initialize result        // Pick a starting point        for (let i = 0; i<n; i++)        {            if (str[i] == '1')            {                // Search for all possible ending point                for (let j = i + 1; j< n; j++)                {                    if (str[j] == '1')                        res++;                }            }        }        return res;    }         // Driver program to test the above function    let string = "00100101";    let n=string.length;    document.write(countSubStr(string,n));              // This code is contributed by rag2127     </script>
Output: 
3
Time Complexity of the above solution is O(n2). We can find count in O(n) using a single traversal of input string. Following are steps. a) Count the number of 1’s. Let the count of 1’s be m. b) Return m(m-1)/2 The idea is to count total number of possible pairs of 1’s. 
C++
Java
Python3
C#
PHP
Javascript
// A O(n) C++ program to count number of// substrings starting and ending with 1#include<iostream> using namespace std; int countSubStr(char str[]){   int m = 0; // Count of 1's in input string    // Traverse input string and count of 1's in it   for (int i=0; str[i] !='\0'; i++)   {        if (str[i] == '1')           m++;   }    // Return count of possible pairs among m 1's   return m*(m-1)/2;} // Driver program to test above functionint main(){  char str[] = "00100101";  cout << countSubStr(str);  return 0;}
// A O(n) C++ program to count number of substrings//starting and ending with 1 class CountSubString{    int countSubStr(char str[], int n)    {        int m = 0; // Count of 1's in input string         // Traverse input string and count of 1's in it        for (int i = 0; i < n; i++)        {            if (str[i] == '1')                m++;        }         // Return count of possible pairs among m 1's        return m * (m - 1) / 2;    }     // Driver program to test the above function    public static void main(String[] args)    {        CountSubString count = new CountSubString();        String string = "00100101";        char str[] = string.toCharArray();        int n = str.length;        System.out.println(count.countSubStr(str, n));    }}
# A Python3 program to count number of# substrings starting and ending with 1 def countSubStr(st, n) :     # Count of 1's in input string    m = 0       # Traverse input string and    # count of 1's in it    for i in range(0, n) :        if (st[i] == '1') :            m = m + 1             # Return count of possible    # pairs among m 1's    return m * (m - 1) // 2      # Driver program to test above functionst = "00100101";list(st)n= len(st)print(countSubStr(st, n), end="")  # This code is contributed# by Nikita Tiwari.
// A O(n) C# program to count// number of substrings starting// and ending with 1using System; class GFG{int countSubStr(char []str, int n){    int m = 0; // Count of 1's in               // input string     // Traverse input string and    // count of 1's in it    for (int i = 0; i < n; i++)    {        if (str[i] == '1')            m++;    }     // Return count of possible    // pairs among m 1's    return m * (m - 1) / 2;} // Driver Codepublic static void Main(String[] args){    GFG count = new GFG();    String strings = "00100101";    char []str = strings.ToCharArray();    int n = str.Length;    Console.Write(count.countSubStr(str, n));}} // This code is contributed by princiraj
<?php// A simple PHP program to count number of// substrings starting and ending with 1 function countSubStr($str){    $m = 0; // Initialize result     // Pick a starting point    for ($i = 0; $i < strlen($str); $i++)    {        if ($str[$i] == '1')        {            $m++;        }    }         // Return count of possible    // pairs among m 1's    return $m * ($m - 1) / 2;} // Driver Code$str = "00100101";echo countSubStr($str); // This code is contributed// by Akanksha Rai?>
<script>// A O(n) javascript program to count number of substrings//starting and ending with 1     function countSubStr(str,n)    {        let m = 0; // Count of 1's in input string          // Traverse input string and count of 1's in it        for (let i = 0; i < n; i++)        {            if (str[i] == '1')                m++;        }          // Return count of possible pairs among m 1's        return m * Math.floor((m - 1) / 2);    }         // Driver program to test the above function    let str = "00100101";    let n = str.length;    document.write(countSubStr(str, n));         //  This code is contributed by avanitrachhadiya2155</script>
Output:  
3
 
YouTubeGeeksforGeeks500K subscribersCount number of substrings that start and end with 1 in a Binary String | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=h8UZKBq1ZR8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
shrikanth13
princiraj1992
ukasp
Akanksha_Rai
rag2127
avanitrachhadiya2155
madarsh986
ashissingh640
Amazon
binary-string
Arrays
Strings
Amazon
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Reverse a string in Java
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
Python program to check if a string is palindrome or not