Skip to main content
Back to problems
#696
Easy Algorithms

Count binary substrings

Two Pointers String
70.3% acceptance
Feb 20, 2026
4631
972
Given a binary string s, return the number of non-empty substrings that have equal numbers of 0's and 1's grouped consecutively.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_binary_substrings(s: String) -> i32 {
    let s = s.as_bytes();
    let mut result = 0;
    let mut prev = 0;
    let mut cur = 1;
    for i in 1..s.len() {
      if s[i] == s[i - 1] {
        cur += 1;
      } else {
        prev = cur;
        cur = 1;
      }
      if prev >= cur {
        result += 1;
      }
    }
    result
  }
}