Skip to content
Problem 696 · LeetCode 696(opens in a new tab)

Count Binary Substrings

EasyStrings

You get a string s made only of the characters 0 and 1. Count its substrings (contiguous, non-empty) that contain as many 0s as 1s and have all their 0s side by side and all their 1s side by side. So "0011" and "10" qualify, but "0101" does not.

The same text at two different positions counts twice: you are counting positions, not distinct strings.

Example 1

Input:  s = "011100"
Output: 3
Why:    "01", "10" and "1100"
2 more examples and the constraints

Example 2

Input:  s = "1010"
Output: 3
Why:    "10", "01", "10": each neighbour pair

Example 3

Input:  s = "000"
Output: 0
Why:    there are no 1s to balance anything

Constraints

  • 1 ≤ length of s ≤ 100,000
  • every s[i] is '0' or '1'

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Expand from every startO(n²)
  2. Neighbouring run lengthsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 charactersVerdict
Expand from every startO(n²)
Mention it, then move on
Neighbouring run lengthsO(n)
Best; one pass, three counters

n = length of s.

Edge cases to test

  • A single character. "0" has no second run, so the answer is 0.
  • Only one kind of bit. "000" also gives 0.
  • Alternating bits. "1010" has runs of 1, so every boundary adds 1: n − 1 in total.
  • Two long runs. "000111" gives min(3, 3) = 3: "01", "0011", "000111".
  • Uneven neighbours. "0001" gives min(3, 1) = 1, not 3.

Common mistakes

  • Forgetting the boundary after the loop, so the last pair of runs is never counted.
  • Adding max(prev, cur) or prev + cur instead of min(prev, cur).
  • Counting only distinct substrings, when repeats at different positions all count.

How to talk through it

  1. 1Clarify. Do repeats at different positions count separately? Can the string have only one kind of bit?
  2. 2Give the brute force. Each start gives at most one match; checking it is O(n), so O(n²) overall.
  3. 3Spot the runs. Every valid substring straddles one boundary, and a boundary between runs a and b gives min(a, b).
  4. 4Code two counters. Keep prev and cur, add min at each change and once at the end.
  5. 5Test out loud. Run "000", "1010" and "0001" to check the end case and the min.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?