Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Split the binary string into substrings with equal number of 0s and 1s
Next article icon

Count of substrings that start and end with 1 in given Binary String

Last Updated : 03 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

Examples:

Input: “00100101”
Output: 3
Explanation: three substrings are “1001”, “100101” and “101”

Input: “1001”
Output: 1
Explanation: one substring “1001”

Recommended Practice
Count Substrings
Try It!

Count of substrings that start and end with 1 in given Binary String using Nested Loop:

A Simple Solution is to run two loops. Outer loops pick every 1 as a starting point and the inner loop searches for ending 1 and increments count whenever it finds 1.

Below is the implementation of above approach:

C++




// 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 point
    for (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 function
int main()
{
    char str[] = "00100101";
    cout << countSubStr(str);
    return 0;
}
 
 

Java




// A simple Java 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));
    }
}
 
 

Python3




# 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 function
st = "00100101"
list(st)
n = len(st)
print(countSubStr(st, n), end="")
 
 
# This code is contributed
# by Nikita Tiwari.
 
 

C#




// A simple C# program to count number of
// substrings starting and ending with 1
using 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 Code
    public 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




<?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
?>
 
 

Javascript




<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: O(N2), 
Auxiliary Space: O(1)

Count of substrings that start and end with 1 in a given Binary String using Subarray count:

We know that if count of 1’s is m, then there will be m * (m – 1) / 2 possible subarrays.

Follow the steps to solve the problem:

  • Count the number of 1’s. Let the count of 1’s be m. 
  • Return m(m-1)/2 

Below is the implementation of above approach:

C++




// 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 function
int main()
{
    char str[] = "00100101";
    cout << countSubStr(str);
    return 0;
}
 
 

Java




// A O(n) Java 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));
    }
}
 
 

Python3




# 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 function
st = "00100101"
list(st)
n = len(st)
print(countSubStr(st, n), end="")
 
 
# This code is contributed
# by Nikita Tiwari.
 
 

C#




// A O(n) C# program to count
// number of substrings starting
// and ending with 1
using 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 Code
    public 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




<?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
?>
 
 

Javascript




<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

Time Complexity: O(N), where n is the length of the string.
Auxiliary Space: O(1).

Count of substrings that start and end with 1 in given Binary String using Recursion:

This approach is the same as the above approach but here to calculate the count of 1s we use recursion.

Follow the steps to solve the problem:

  • Count the number of 1’s using recursion. Let the count of 1’s be m. 
  • Return m(m-1)/2 

Below is the implementation of above approach:

C++




// A O(n) C++ program to count number of
// substrings starting and ending with 1
#include <bits/stdc++.h>
using namespace std;
 
int helper(int n, char str[], int i)
{
    // if 'i' is on the last index
    if (i == n - 1)
        return (str[i] == '1') ? 1 : 0;
 
    // if current char is 1
    // add 1 to the answer
    if (str[i] == '1')
        return 1 + helper(n, str, i + 1);
 
    // if it is zero
    else
        return helper(n, str, i + 1);
}
 
int countSubStr(char str[])
{
    int n = strlen(str);
    // counting the number of 1's in the string
    int count = helper(n, str, 0);
 
    // return the number of combinations
    return (count * (count - 1)) / 2;
}
 
// Driver program to test above function
int main()
{
    char str[] = "00100101";
    cout << countSubStr(str);
    return 0;
}
 
// this code is contributed by rajdeep999
 
 

Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
  static int helper(int n, char str[], int i)
  {
    // if 'i' is on the last index
    if (i == n - 1)
      return (str[i] == '1') ? 1 : 0;
 
    // if current char is 1
    // add 1 to the answer
    if (str[i] == '1')
      return 1 + helper(n, str, i + 1);
 
    // if it is zero
    else
      return helper(n, str, i + 1);
  }
 
  static int countSubStr(char str[])
  {
    int n = str.length;
    // counting the number of 1's in the string
    int count = helper(n, str, 0);
 
    // return the number of combinations
    return (count * (count - 1)) / 2;
  }
 
  public static void main (String[] args) {
    char str[] = "00100101".toCharArray();
    System.out.println(countSubStr(str));
  }
}
 
// This code is contributed by aadityaburujwale.
 
 

Python3




class GFG :
    @staticmethod
    def  helper( n,  str,  i) :
       
        # if 'i' is on the last index
        if (i == n - 1) :
            return 1 if (str[i] == '1') else 0
           
        # if current char is 1
        # add 1 to the answer
        if (str[i] == '1') :
            return 1 + GFG.helper(n, str, i + 1)
        else :
            return GFG.helper(n, str, i + 1)
    @staticmethod
    def  countSubStr( str) :
        n = len(str)
         
        # counting the number of 1's in the string
        count = GFG.helper(n, str, 0)
         
        # return the number of combinations
        return int((count * (count - 1)) / 2)
    @staticmethod
    def main( args) :
        str = list("00100101")
        print(GFG.countSubStr(str))
     
 
if __name__=="__main__":
    GFG.main([])
     
    # This code is contributed by aadityaburujwale.
 
 

C#




// Include namespace system
using System;
 
 
public class GFG
{
    public static int helper(int n, char[] str, int i)
    {
        // if 'i' is on the last index
        if (i == n - 1)
        {
            return (str[i] == '1') ? 1 : 0;
        }
       
        // if current char is 1
        // add 1 to the answer
        if (str[i] == '1')
        {
            return 1 + GFG.helper(n, str, i + 1);
        }
        else
        {
            return GFG.helper(n, str, i + 1);
        }
    }
    public static int countSubStr(char[] str)
    {
        var n = str.Length;
       
        // counting the number of 1's in the string
        var count = GFG.helper(n, str, 0);
       
        // return the number of combinations
        return (int)((count * (count - 1)) / 2);
    }
    public static void Main(String[] args)
    {
        char[] str = "00100101".ToCharArray();
        Console.WriteLine(GFG.countSubStr(str));
    }
}
 
// This code is contributed by aadityaburujwale.
 
 

Javascript




// A O(n) JS program to count number of
// substrings starting and ending with 1
function helper(n, str, i)
{
 
    // if 'i' is on the last index
    if (i == n - 1) {
        return (str[i] == '1') ? 1 : 0;
    }
     
    // if current char is 1
    // add 1 to the answer
    if (str[i] == '1') {
        return 1 + helper(n, str, i + 1);
    }
     
    // if it is zero
    else {
        return helper(n, str, i + 1);
    }
}
 
function countSubStr(str) {
    let n = str.length;
     
    // counting the number of 1's in the string
    let count = helper(n, str, 0);
     
    // return the number of combinations
    return (count * (count - 1)) / 2;
}
 
// Driver program to test above function
console.log(countSubStr("00100101"));
 
// This code is contributed by akashish_
 
 
Output
3

Time Complexity: O(N), Traversing over the string of size N
Auxiliary Space: O(N), for recursion call stack



Next Article
Split the binary string into substrings with equal number of 0s and 1s
author
kartik
Improve
Article Tags :
  • Arrays
  • DSA
  • Strings
  • Amazon
  • binary-string
Practice Tags :
  • Amazon
  • Arrays
  • Strings

Similar Reads

  • Different substrings in a string that start and end with given strings
    Given a string s and two other strings begin and end, find the number of different substrings in the string which begin and end with the given begin and end strings. Examples: Input : s = "geeksforgeeks" begin = "geeks" end = "for" Output : 1 Input : s = "vishakha" begin = "h" end = "a" Output : 2 T
    9 min read
  • Count of substrings with equal ratios of 0s and 1s till ith index in given Binary String
    Given a binary string S, the task is to print the maximum number of substrings with equal ratios of 0s and 1s till the ith index from the start. Examples: Input: S = "110001"Output: {1, 2, 1, 1, 1, 2}Explanation: The given string can be partitioned into the following equal substrings: Valid substrin
    9 min read
  • Count of substrings of a given Binary string with all characters same
    Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = “011”Output: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
    10 min read
  • Split the binary string into substrings with equal number of 0s and 1s
    Given a binary string str of length N, the task is to find the maximum count of consecutive substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.Example: Input
    8 min read
  • Count of substrings in a Binary String that contains more 1s than 0s
    Given a binary string s, the task is to calculate the number of such substrings where the count of 1's is strictly greater than the count of 0's. Examples Input: S = "110011"Output: 11Explanation: Substrings in which the count of 1's is strictly greater than the count of 0's are { S[0]}, {S[0], S[1]
    15+ min read
  • Count of non-overlapping sub-strings "101" and "010" in the given binary string
    Given binary string str, the task is to find the count of non-overlapping sub-strings of either the form "010" or "101". Examples: Input: str = "10101010101" Output: 3 str[0..2] = "101" str[3..5] = "010" str[6..8] = "101"Input: str = "111111111111110" Output: 0 Approach: Initialize count = 0 and for
    5 min read
  • Count of Reverse Bitonic Substrings in a given String
    Given a string S, the task is to count the number of Reverse Bitonic Substrings in the given string. Reverse bitonic substring: A string in which the ASCII values of the characters of the string follow any of the following patterns: Strictly IncreasingStrictly decreasingDecreasing and then increasin
    8 min read
  • Count substrings of a given string whose anagram is a palindrome
    Given a string S of length N containing only lowercase alphabets, the task is to print the count of substrings of the given string whose anagram is palindromic. Examples: Input: S = "aaaa"Output: 10Explanation:Possible substrings are {"a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"}. Sinc
    10 min read
  • Maximum count of unique index 10 or 01 substrings in given Binary string
    Given a binary string str of length N, the task is to count the maximum number of adjacent pairs of form "01" or "10" that can be formed from the given binary string when one character can be considered for only one pair. Note: Adjacent pair means pair formed using adjacent characters. Examples: Inp
    5 min read
  • Count the number of Binary Strings which have X 1's and Y 0's
    Given two integers X and Y, the task is to count the number of binary strings which have X 1's and Y 0's and there are no two consecutive 1's in the string. Examples: Input: X = 2, Y = 2Output: 3Explanation: 1010, 0101, 1001 - these are 3 strings that can be possible such that there are no two conse
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences