![]() |
VOOZH | about |
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: 11
Explanation: Substrings in which the count of 1's is strictly greater than the count of 0's are {1}, {11}, {110}, {11001}, {110011}, {1}, {10011}, {011}, {1}, {11}, {1}.Input: s = "011"
Output: 4
Explanation: There are 4 substring which has more 1s than 0s. i.e {011}, {1}, {11} and {1}.Input: s = "0000"
Output: 0
Explanation: There is no substring with more 1s than 0s.
Table of Content
The simplest approach to solve the problem is to generate all substrings and count the number of 1s and 0s in each substring. Increase the count of those substrings that contain the count of 1s greater than the count of 0s. Finally, print the count obtained.
11
The idea is to treat '1' as +1 and '0' as -1, so a substring with a positive sum has more 1s than 0s. We use prefix balances to avoid checking every substring separately. A frequency array stores how many times each balance occurs, while minus tracks invalid states where zeros are greater than or equal to ones. By updating these values dynamically, we count all valid substrings in linear time.
Consider the following dry run for better understanding: s = "011"
Final answer : ans = 4. Valid Substrings : {011}, {1}, {11} and {1}.
11