Count of substrings that start and end with 1 in given Binary String
Last Updated :
09 Jul, 2025
Given a binary string s, the task is to count all substrings that start and end with the character '1'. A valid substring must have both its first and last characters as '1', and can include one or more number of characters in between.
Examples:
Input: s = "00100101"
Output: 3
Explanation: Valid substrings are "1001", "100101", and "101", all starting and ending with '1'.
Input: s = "1001"
Output: 1
Explanation: Only one valid substring: "1001", which starts and ends with '1'.
Input: s = "111"
Output: 3
Explanation: Valid substrings are "11" (first and second), "11" (second and third), and "111" (entire string).
[Brute-Force Approach] Using Two Nested Loops - O(n^2) Time and O(1) Space
The idea is to explore every possible substring of the given binary string using two nested loops. The thought process is that a valid substring must start and end with '1', so we check every pair of indices to see if both ends are '1'. For every such valid pair, we increment the count. This approach ensures we count all continuous segments that satisfy the condition, regardless of length or content in between.
C++
// C++ program to count all substrings that start
// and end with '1' using Brute-Force Approach
#include <iostream>
#include <string>
using namespace std;
// Function to count valid substrings
int binarySubstring(string &s) {
int n = s.length();
int count = 0;
// Traverse all substrings using nested loops
for (int i = 0; i < n; i++) {
// If starting character is '1'
if (s[i] == '1') {
for (int j = i + 1; j < n; j++) {
// If ending character is also '1'
if (s[j] == '1') {
count++;
}
}
}
}
return count;
}
// Driver code
int main() {
string s = "00100101";
cout << binarySubstring(s);
return 0;
}
Java
// Java program to count all substrings that start
// and end with '1' using Brute-Force Approach
class GfG {
// Function to count valid substrings
static int binarySubstring(String s) {
int n = s.length();
int count = 0;
// Traverse all substrings using nested loops
for (int i = 0; i < n; i++) {
// If starting character is '1'
if (s.charAt(i) == '1') {
for (int j = i + 1; j < n; j++) {
// If ending character is also '1'
if (s.charAt(j) == '1') {
count++;
}
}
}
}
return count;
}
// Driver code
public static void main(String[] args) {
String s = "00100101";
System.out.println(binarySubstring(s));
}
}
Python
# Python program to count all substrings that start
# and end with '1' using Brute-Force Approach
# Function to count valid substrings
def binarySubstring(s):
n = len(s)
count = 0
# Traverse all substrings using nested loops
for i in range(n):
# If starting character is '1'
if s[i] == '1':
for j in range(i + 1, n):
# If ending character is also '1'
if s[j] == '1':
count += 1
return count
# Driver code
if __name__ == "__main__":
s = "00100101"
print(binarySubstring(s))
C#
// C# program to count all substrings that start
// and end with '1' using Brute-Force Approach
using System;
class GfG {
// Function to count valid substrings
public static int binarySubstring(string s) {
int n = s.Length;
int count = 0;
// Traverse all substrings using nested loops
for (int i = 0; i < n; i++) {
// If starting character is '1'
if (s[i] == '1') {
for (int j = i + 1; j < n; j++) {
// If ending character is also '1'
if (s[j] == '1') {
count++;
}
}
}
}
return count;
}
// Driver code
public static void Main() {
string s = "00100101";
Console.WriteLine(binarySubstring(s));
}
}
JavaScript
// JavaScript program to count all substrings that start
// and end with '1' using Brute-Force Approach
// Function to count valid substrings
function binarySubstring(s) {
let n = s.length;
let count = 0;
// Traverse all substrings using nested loops
for (let i = 0; i < n; i++) {
// If starting character is '1'
if (s[i] === '1') {
for (let j = i + 1; j < n; j++) {
// If ending character is also '1'
if (s[j] === '1') {
count++;
}
}
}
}
return count;
}
// Driver code
let s = "00100101";
console.log(binarySubstring(s));
[Expected Approach] Count No. of 1's - O(n) Time and O(1) Space
The idea is to count '1's in the string. The thought process is that for every pair of '1's, one valid substring can be formed. So, if there are m '1's, then the total number of such pairs is m × (m - 1) / 2, which gives us the count of valid substrings. We use recursion here purely to demonstrate a different way of counting without loops.
Why m × (m - 1) / 2?
- Suppose there are m occurrences of '1' in the string.
- To form a valid substring, we need to pick two different positions where '1' appears — one as the start and one as the end.
- The number of ways to choose 2 different '1's from m positions is the combinatorial formula:
- m × (m - 1) / 2, which is nC2 (number of ways to choose 2 elements from m).
- Each such pair (i, j) where i < j gives a unique substring that starts and ends with '1'.
C++
// C++ program to count all substrings that start
// and end with '1' using count of 1's
#include <iostream>
#include <string>
using namespace std;
// Function to count valid substrings
int binarySubstring(string &s) {
int ones = 0;
// Count of '1's using loop
for (int i = 0; i < s.length(); i++) {
if (s[i] == '1') {
ones++;
}
}
// Return total substrings = m * (m - 1) / 2
return (ones * (ones - 1)) / 2;
}
// Driver code
int main() {
string s = "00100101";
cout << binarySubstring(s);
return 0;
}
Java
// Java program to count all substrings that start
// and end with '1' using count of 1's
class GfG {
// Function to count valid substrings
static int binarySubstring(String s) {
int ones = 0;
// Count of '1's using loop
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '1') {
ones++;
}
}
// Return total substrings = m * (m - 1) / 2
return (ones * (ones - 1)) / 2;
}
public static void main(String[] args) {
String s = "00100101";
System.out.println(binarySubstring(s));
}
}
Python
# Python program to count all substrings that start
# and end with '1' using count of 1's
# Function to count valid substrings
def binarySubstring(s):
ones = 0
# Count of '1's using loop
for i in range(len(s)):
if s[i] == '1':
ones += 1
# Return total substrings = m * (m - 1) / 2
return (ones * (ones - 1)) // 2
if __name__ == "__main__":
s = "00100101"
print(binarySubstring(s))
C#
// C# program to count all substrings that start
// and end with '1' using count of 1's
using System;
class GfG {
// Function to count valid substrings
public static int binarySubstring(string s) {
int ones = 0;
// Count of '1's using loop
for (int i = 0; i < s.Length; i++) {
if (s[i] == '1') {
ones++;
}
}
// Return total substrings = m * (m - 1) / 2
return (ones * (ones - 1)) / 2;
}
public static void Main() {
string s = "00100101";
Console.WriteLine(binarySubstring(s));
}
}
JavaScript
// JavaScript program to count all substrings that start
// and end with '1' using count of 1's
// Function to count valid substrings
function binarySubstring(s) {
let ones = 0;
// Count of '1's using loop
for (let i = 0; i < s.length; i++) {
if (s[i] === '1') {
ones++;
}
}
// Return total substrings = m * (m - 1) / 2
return (ones * (ones - 1)) / 2;
}
let s = "00100101";
console.log(binarySubstring(s));
Binary String | DSA Problem
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