VOOZH about

URL: https://www.geeksforgeeks.org/dsa/given-binary-string-count-number-substrings-start-end-1/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 17 Feb, 2026

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).

[Naive Approach] Using Two Nested Loops - O(n2) 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.


Output
3

[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.

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'.

Output
3
Comment
Article Tags: