LeetCode Entry
696. Count Binary Substrings
Count substrings of 01 and 10 window
696. Count Binary Substrings easy blog post substack youtube

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()
}