LeetCode Entry

696. Count Binary Substrings

19.02.2026 easy 2026 kotlin rust

Count substrings of 01 and 10 window

696. Count Binary Substrings easy blog post substack youtube

ca5bca1d-de86-418b-815f-1df4df895c62 (1).webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1274

Problem TLDR

Count substrings of 01 and 10 #easy #sliding_window

Intuition

Count consequent zeros and ones. Slide pair-wise res += min(prev, curr).

Approach

  • the fun solution is to split the string
  • itertools in Rust allow nested windows without vec allocation

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code

// 69ms
    fun countBinarySubstrings(s: String) = s
    .replace("01", "0 1").replace("10", "1 0").split(" ")
    .zipWithNext { a, b -> min(a.length, b.length)}.sum()
// 0ms
	pub fn count_binary_substrings(s: String) -> i32 {
        s.as_bytes().chunk_by(|a,b|a==b).map(|c|c.len() as i32)
        .tuple_windows().map(|(a,b)|a.min(b)).sum()
    }