![]() |
VOOZH | about |
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).
Table of Content
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.
3
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 ?
3