Given a binary string s
, return the number of non-empty substrings that have the same number of 0’s and 1’s, and all the 0’s and all the 1’s in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Before getting into the solution, let’s clarify any potential questions:
s
?
s
’s length can be up to 10^5
.To solve this problem, we will take the following approach:
Here’s how we can implement this strategy:
def countBinarySubstrings(s: str) -> int:
groups = []
count = 1
# Traverse through the string to build the groups list
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1
else:
groups.append(count)
count = 1
groups.append(count) # Append the last group
# Count valid substrings
valid_substring_count = 0
for i in range(1, len(groups)):
valid_substring_count += min(groups[i], groups[i - 1])
return valid_substring_count
Time Complexity: O(n), where n is the length of the string. We traverse the string once to build the groups and then again to count valid substrings.
Space Complexity: O(n) in the worst case, for storing the groups list.
This code efficiently counts the binary substrings by leveraging the grouped nature of consecutive characters and ensures minimal time and space overhead.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?