#696

Count Binary Substrings

Easy
Two PointersStringTwo PointersSliding WindowArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the observation that valid substrings can be counted by grouping consecutive '0's and '1's. By counting the lengths of these groups, we can determine how many valid substrings can be formed.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the lengths of consecutive '0's and '1's and store them in an array.
  2. 2Step 2: Iterate through the array of counts and for each pair of consecutive counts, the number of valid substrings is the minimum of the two counts.
  3. 3Step 3: Sum these minimum counts to get the total number of valid substrings.
solution.py18 lines
1# Full working Python code
2
3def countBinarySubstrings(s):
4    groups = []
5    count = 1
6    for i in range(1, len(s)):
7        if s[i] == s[i - 1]:
8            count += 1
9        else:
10            groups.append(count)
11            count = 1
12    groups.append(count)  # Append the last group
13
14    result = 0
15    for i in range(1, len(groups)):
16        result += min(groups[i - 1], groups[i])
17    return result
18

Complexity note: This complexity is due to the need to store the lengths of groups of '0's and '1's, but we only traverse the string a couple of times.

  • 1Grouping consecutive characters helps in efficiently counting valid substrings.
  • 2The minimum of consecutive counts determines the number of valid substrings that can be formed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.