Count Binary Substrings Problem
Description
LeetCode Problem 696.
Give 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 <= 10^5
- s[i] is either '0' or '1'.
Solution
Approach: Count Runs of Equal Characters
Checking every substring takes O(n2) time or worse. Instead, split s into runs, maximal blocks of equal characters. For "00110011" the runs have lengths 2, 2, 2, 2.
A valid substring is some 0s followed by the same number of 1s (or the other way around), so it always sits across the border of two neighbouring runs. If the left run has length a and the right run has length b, the valid substrings across that border are "01", "0011", … up to length 2 * min(a, b): exactly min(a, b) of them. For example, runs 000 and 11 give "01" and "0011".
So the answer is the sum of min(a, b) over every pair of neighbouring runs. We only need the lengths of the previous run and the current run:
- Start with
previousRun = 0andcurrentRun = 1(the run ofs[0]). - For each next character: if it equals the one before, grow
currentRun. Otherwise a run just ended: addmin(previousRun, currentRun)to the count, then move on withpreviousRun = currentRunandcurrentRun = 1. - After the loop, add
min(previousRun, currentRun)once more for the last border. Forgetting this step is the usual bug; it loses the substrings that end at the last character.
Complexity: O(n) time and O(1) space, where n is the length of s.
class Solution:
def countBinarySubstrings(self, s: str) -> int:
count = 0
previous_run = 0 # length of the run of equal characters before the current one
current_run = 1 # length of the run that s[i] belongs to
for i in range(1, len(s)):
if s[i] == s[i - 1]:
current_run += 1
else:
# Two neighbouring runs form min(previous, current) valid substrings.
count += min(previous_run, current_run)
previous_run = current_run
current_run = 1
count += min(previous_run, current_run) # the last pair of runs
return count
Now write it from memory
Close the write-up and solve it yourself against the tests.