FastPrepCount Binary Substrings
Problems/Count Binary Substrings

Count Binary Substrings

Microsoft logoMicrosoft● EasyFULLTIMEINTERNOA
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source explicitly identifies LeetCode 696, Count Binary Substrings, and records the adjacent-run O(n)-time, O(1)-space method. It does not reproduce the platform signature, examples, or numeric bounds; this practice version is an approximately 99% match.

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

  • Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
  • Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
  • Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
All Microsoft interview questionsSee Microsoft hiring insights
Saved
class Solution {
    public int countBinarySubstrings(String s) {
        // Write your code here.
    }
}
Checking account…