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 made only of the characters 0 and 1, count its non-empty substrings that have as many 0s as 1s, with all the 0s next to each other and all the 1s next to each other. A substring that appears in several places is counted once for each place.

Example 1
Input: s = "00110011"
Output: 6
Explanation: "0011", "01", "1100", "10", "0011" and "01".
Example 2
Input: s = "10101"
Output: 4
Explanation: "10", "01", "10" and "01".
Solution

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.

The string 00011 is a run of 0s of length 3 next to a run of 1s of length 2. Growing outward from the boundary gives 01 and 0011. 000111 would need a third 1, so the boundary gives min(3, 2) = 2 substrings.

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. prevRun is the length of the run before the current one, and curRun is the length of the current run.

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) is added for that boundary. Then the run that ended becomes the previous run. prevRun starts at 0, because the first run has no run before it, so the first change of digit adds min(0, curRun) = 0.

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 works in these steps:

  1. First, set prevRun to 0 and curRun to 1, because the first character on its own is already a run of length 1. The total, count, starts at 0.
  2. A loop moves i from the second character to the end and compares s.charAt(i) with the character before it. The same digit makes curRun one longer.
  3. A different digit means the current run is complete. Add Math.min(prevRun, curRun) to count for the boundary before that run, copy curRun into prevRun, and set curRun back to 1 for the run that starts at i.
  4. After the loop, return count plus Math.min(prevRun, curRun), the boundary before the last run.

The main method runs both examples, "00011" from the picture, "0001111000" with runs of different lengths, "01", "1111" with no boundary at all, and the single character "0".

Java
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:

Output
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 s with the one before it once, and each boundary costs one min and two assignments.
  • Space: O(1), because only prevRun, curRun and count are kept, however long the string is. The version with a list of run lengths needs O(n).

Splitting a string into runs of equal characters also drives Count and Say.