Taro Logo

Count Binary Substrings

#1 Most AskedEasy
Topics:
ArraysStringsTwo Pointers

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.

Example 1:

Input: s = "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
Notice that some of these substrings repeat and are counted the number of times they occur.
Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.

Example 2:

Input: s = "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.

Constraints:

  • 1 <= s.length <= 105
  • s[i] is either '0' or '1'.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the binary string `s` that we can expect?
  2. Can the input string be empty, or contain only '0's or only '1's?
  3. When the problem states that substrings occurring multiple times should be counted multiple times, does this mean identical substring instances at different indices are treated as distinct valid substrings?
  4. Are we guaranteed that the input string `s` will only contain characters '0' and '1'?
  5. Should the returned count be an integer, and what should be returned if no valid substrings exist?

Brute Force Solution

Approach

The brute force approach to solving this problem involves examining every single possible section of the given text to see if it meets our specific rules for alternating zeros and ones. We will systematically test every possible group of characters from beginning to end to count how many valid ones we can find.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first character of the sequence.
  2. Try forming a small group starting at this position by including the next adjacent character to see if they form a valid pair of alternating zeros and ones of equal length.
  3. If that works, count it as a valid group and expand your view to try even larger groups starting from the same spot, checking if they contain an equal number of consecutive zeros followed by an equal number of consecutive ones, or vice versa.
  4. Keep expanding until the sequence of characters is no longer valid or you run out of text.
  5. Once you have tested all possible groups starting from the first position, move your starting point to the second character in the sequence.
  6. Repeat the entire process of testing every possible group size from this new starting point.
  7. Continue this process of shifting your starting point one step to the right and testing every possible group size until you have checked every single combination of characters in the entire text.
  8. Finally, add up all the valid groups you discovered along the way to get your total count.

Code Implementation

class Solution:
    def countBinarySubstrings(self, binary_string: str) -> int:
        valid_group_count = 0
        string_length = len(binary_string)
        
        # Iterate through every possible starting position to examine all substring combinations
        for starting_index in range(string_length):
            current_character = binary_string[starting_index]
            consecutive_first_count = 0
            consecutive_second_count = 0
            second_character = ""
            
            for current_index in range(starting_index, string_length):
                character_to_check = binary_string[current_index]
                
                if second_character == "":
                    if character_to_check == current_character:
                        consecutive_first_count += 1
                    else:
                        second_character = character_to_check
                        consecutive_second_count += 1
                else:
                    if character_to_check == second_character:
                        consecutive_second_count += 1
                    else:
                        break
                
                # Ensure we have matched segments of equal length before counting a valid substring
                if consecutive_first_count > 0 and consecutive_second_count > 0:
                    if consecutive_first_count == consecutive_second_count:
                        valid_group_count += 1
                        
        return valid_group_count

Big(O) Analysis

Time Complexity
O(n²) – The brute force strategy uses a primary loop to shift the starting position across each of the n characters in the text, and a nested process that expands the group size outward from that start point. For the first character, we test up to n-1 potential subgroups, for the second we test n-2, and so on. This cumulative checking leads to approximately n * n / 2 total operations, which simplifies to a quadratic runtime complexity of O(n²).
Space Complexity
O(1) – The brute force approach as described operates entirely on the input string by using a few primitive integer variables to track starting indices, current positions, and group lengths. No auxiliary data structures, temporary lists, or recursion stack frames are utilized during the systematic testing of substrings. Therefore, the extra memory required remains constant regardless of the input string length N, resulting in an optimal auxiliary space complexity.

Optimal Solution

Approach

Instead of checking every single possible grouping, the optimal approach looks at the text as a sequence of repeating blocks of identical characters. By measuring the length of each consecutive block, we can instantly determine how many valid binary substrings can be formed where zeros and ones group together equally.

Here's how the algorithm would work step-by-step:

  1. Scan through the text from start to finish and measure the length of every unbroken block of identical characters.
  2. Keep track of how long the previous block was while you measure the current block.
  3. Whenever you finish measuring a new block, compare its length to the length of the block that came right before it.
  4. Take the smaller of these two lengths, because that tells you how many balanced groups of zeros and ones can safely pair up between the two neighboring blocks.
  5. Add that number to your running total of valid substrings.
  6. Shift your focus forward so the current block becomes the previous block, and measure the next incoming block.
  7. Continue this process until you reach the end of the text, giving you the final count without wasting time on brute-force checks.

Code Implementation

def count_binary_substrings(binary_string):
    total_substring_count = 0
    previous_block_length = 0
    current_block_length = 1
    string_length = len(binary_string)

    # We scan through the text to measure lengths of unbroken identical character blocks.
    for character_index in range(1, string_length):
        if binary_string[character_index] == binary_string[character_index - 1]:
            current_block_length += 1
        else:
            # The smaller block length dictates how many valid pairs can form between neighbors.
            total_substring_count += min(previous_block_length, current_block_length)
            previous_block_length = current_block_length
            current_block_length = 1

    # Handle the final neighboring block comparison after the loop finishes.
    total_substring_count += min(previous_block_length, current_block_length)

    return total_substring_count

Big(O) Analysis

Time Complexity
O(n) – The algorithm performs a single pass from start to finish to scan through the text and measure the lengths of consecutive identical character blocks. For a string of length n, each character is examined a constant number of times as we track the current and previous block lengths. This linear scanning process avoids nested loops and pair checking entirely. The total operations scale directly with the input size n, which simplifies cleanly to O(n).
Space Complexity
O(1) – The algorithm only maintains a few primitive integer variables to keep track of the previous block length, the current block length, and the running total of valid substrings. These scalar variables occupy a constant amount of memory regardless of the input string length N. No extra data structures, arrays, or recursive stack frames are created during the execution. Therefore, the auxiliary space complexity remains strictly constant as the input size grows.

Edge Cases

String with a single character like '0' or '1'
How to Handle:
Return zero because a single character cannot form a substring with an equal number of adjacent zeros and ones.
String with only identical characters like '0000' or '1111'
How to Handle:
The counting logic sees no alternating groups and naturally returns zero valid substrings.
Alternating binary string like '010101'
How to Handle:
Each adjacent pair of '0' and '1' contributes one valid substring, summing them up correctly via adjacent run comparisons.
Maximal length strings up to the problem constraints
How to Handle:
A linear scan algorithm running in O(n) time complexity easily processes large strings within standard execution time limits.
Asymmetric group sizes like '0001'
How to Handle:
The minimum function between adjacent run lengths ensures we only count the overlapping valid substrings constrained by the smaller group.
Multiple consecutive transitions like '00110011'
How to Handle:
Iterating through the counted run lengths group by group accumulates the pairs accurately without missing any combinations.
Large integer overflow during substring summation
How to Handle:
Using 64-bit integer types for the total count accumulator prevents overflow when the string length reaches its maximum constraint.
0/1 completed