FastPrepCount Binary Substrings
Problem · String

Count Binary Substrings

Learn this problem
EasyMicrosoft logoMicrosoftFULLTIMEOA
See Microsoft hiring insights

Problem statement

Given a binary string s, return the number of nonempty contiguous substrings that contain the same number of 0 and 1 characters, with every 0 and every 1 grouped consecutively inside the substring.

Substrings are counted by their positions, so equal text occurring at different positions is counted more than once.

Function

countBinarySubstrings(s: String) → int

Examples

Example 1

s = "00110011"return = 6

The valid occurrences are 0011, 01, 1100, 10, 0011, and 01.

Example 2

s = "10101"return = 4

Each adjacent pair forms one valid substring, and no longer substring has exactly two consecutive groups.

Constraints

  • 1 <= s.length <= 100000.
  • Every character of s is 0 or 1.

More Microsoft problems

drafts saved locally
public int countBinarySubstrings(String s) {
    // Write your code here.
}
s"00110011"
expected6
checking account