Count of substrings that start and end with 1 in given Binary String
Last Updated : 03 Feb, 2023
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"
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>
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>
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_
Time Complexity: O(N), Traversing over the string of size N
Auxiliary Space: O(N), for recursion call stack
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read