Count Binary Substrings
Count the substrings made of a block of 0s next to an equal block of 1s, using the lengths of neighbouring runs.
Given a string s
Example 1
Output: 6
Explanation: "0011", "01", "1100", "10", "0011" and "01".
Example 2
Output: 4
Explanation: "10", "01", "10" and "01".
The Idea
A string of only 0s and 1s is called a binary string. The pieces we count look like a few 0s followed by just as many 1s, such as "0011", or a few 1s followed by just as many 0s, such as "10". The string "0110" does not count: it has two of each digit, but its 0s are split apart.
Read Example 1, "00110011", from the left. "0011" at the start counts, and so does the "01" in its middle. The two 1s that follow give "1100" and "10", and the end gives "0011" and "01" again, six in all. Each of them sits across a place where the digit changes, with half its characters on each side.
A counted substring changes digit exactly once, so it never reaches past the stretches of equal digits on either side of that change. So the question becomes: how many counted substrings fit across one change of digit?
A stretch of equal digits is called a run. "00110011" has four runs: "00", "11", "00" and "11". The place where one run ends and the next begins is a boundary. Look at the picture below. It shows a shorter string, "00011": a run of 0s of length 3 next to a run of 1s of length 2.
Counted substrings grow outward from the boundary, one character on each side at a time. The row "01" takes one character from each run, and the row "0011" takes two. The last row, "000111", would need a third 1, and there is none. So the shorter run sets the limit: this boundary gives min(3, 2) = 2 substrings, where min is the smaller of two numbers.
The answer is therefore the sum of min over every two neighbouring runs. In Example 1 the runs have lengths 2, 2, 2 and 2, so its three boundaries give 2 + 2 + 2 = 6. Example 2, "10101", has five runs of length 1, and its four boundaries give 1 each, 4 in all.
Solution Approach
After a look at why checking every substring is slow, turning the idea into code means settling three things: how to find the runs, what to remember about them, and how to count the last boundary.
Checking every substring
Why not test each substring directly? A string of n characters has n(n + 1)/2 substrings, which for 10,000 characters is about 50 million, and testing one can mean reading up to n characters. Counting by boundaries reads each character once instead.
Finding the runs
How do we know where a run ends? Compare each character with the one before it. The same digit makes the current run one longer. A different digit marks a boundary, and a new run of length 1 starts there.
Remembering two run lengths
Which runs need to be remembered? A boundary involves only the two runs on either side of it, so two numbers are enough. prevRuncurRun
When the digit changes, the current run has just ended, so its length is final. That completes the boundary between it and the run before it, and min(prevRun, curRun)prevRun
A simpler version first writes every run length into a list and then adds up the min of each neighbouring pair. It gives the same answer, but the list can grow as long as the string, while two numbers never grow.
Counting the last boundary
Why is one boundary left over? A boundary is added only once the run after it has ended, and that is noticed at the next change of digit. The last run ends with the string, with no change after it. So its boundary is added once more, after every character has been read.
Java Solution
The method countBinarySubstrings
- First, set
to 0 andprevRun to 1, because the first character on its own is already a run of length 1. The total,curRun , starts at 0.count - A loop moves
from the second character to the end and comparesi with the character before it. The same digit makess.charAt(i) one longer.curRun - A different digit means the current run is complete. Add
toMath.min(prevRun, curRun) for the boundary before that run, copycount intocurRun , and setprevRun back to 1 for the run that starts atcurRun .i - After the loop, return
pluscount , the boundary before the last run.Math.min(prevRun, curRun)
The main
public class CountBinarySubstrings {
public static int countBinarySubstrings(String s) {
int prevRun = 0; // length of the run before the current one
int curRun = 1; // length of the current run
int count = 0;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
curRun++; // same digit: the current run grows
} else {
count += Math.min(prevRun, curRun); // the boundary between those two runs
prevRun = curRun;
curRun = 1; // a new run starts at i
}
}
return count + Math.min(prevRun, curRun); // the last boundary
}
public static void main(String[] args) {
System.out.println(countBinarySubstrings("00110011"));
System.out.println(countBinarySubstrings("10101"));
System.out.println(countBinarySubstrings("00011"));
System.out.println(countBinarySubstrings("0001111000"));
System.out.println(countBinarySubstrings("01"));
System.out.println(countBinarySubstrings("1111"));
System.out.println(countBinarySubstrings("0"));
}
}
Running it prints:
6
4
2
6
1
0
0
Example 1 prints 6 and Example 2 prints 4. The third line, 2, matches the picture: "00011" gives min(3, 2). In "0001111000" the runs have lengths 3, 4 and 3, and both boundaries are held to 3 by a run of 0s. So the fourth line is 6, although the run of 1s has four characters.
The 1 for "01" comes entirely from the addition after the loop. The loop sees one change of digit, at the 1, and adds min(0, 1) = 0 for the boundary before the first run. Leaving out the final addition is an easy slip: the method then returns 0 for "01" and 4 instead of 6 for "00110011".
The last two lines are 0. "1111" is a single run with no boundary, and "0" never enters the loop. In both, the final addition is min(0, length of the run) = 0.
Complexity
The method reads the string once and keeps three numbers.
- Time: O(n), because the loop compares each of the n characters of
with the one before it once, and each boundary costs one min and two assignments.s - Space: O(1), because only
,prevRun andcurRun are kept, however long the string is. The version with a list of run lengths needs O(n).count
Splitting a string into runs of equal characters also drives