Count Binary Substrings in Python

🚀 Coding Practice — 696. Count Binary Substrings Today I worked on an interesting string problem that tests pattern observation and grouping logic. 🧠 Problem Statement Given a binary string s, count the number of non-empty substrings where: ✔️ The number of 0s and 1s are equal ✔️ All 0s are grouped together ✔️ All 1s are grouped together Example: Input: "00110011" Output: 6 Valid substrings: "0011", "01", "1100", "10", "0011", "01" 💡 Key Insight Instead of checking all substrings (which would be inefficient ❌), we observe: 👉 The string can be divided into consecutive groups of 0’s and 1’s. 👉 For every pair of adjacent groups, the number of valid substrings is: min(length_of_previous_group, length_of_current_group) Why? Because a valid substring can only be formed between two adjacent groups. 🔍 Example Breakdown For "00110011" Groups: 00 → 2 11 → 2 00 → 2 11 → 2 Now calculate: min(2,2) + min(2,2) + min(2,2) = 2 + 2 + 2 = 6 ✅ Final Answer = 6 🧑💻 Python Implementation class Solution(object): def countBinarySubstrings(self, s): prev_group = 0 curr_group = 1 result = 0 for i in range(1, len(s)): if s[i] == s[i - 1]: curr_group += 1 else: result += min(prev_group, curr_group) prev_group = curr_group curr_group = 1 result += min(prev_group, curr_group) return result ⏱ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) Efficient, clean, and optimal 💯 🔥 What I Learned Pattern recognition is powerful in string problems Group counting can replace brute force substring checking Observing structure reduces complexity from O(n²) → O(n) #Python #DataStructures #Algorithms #CodingPractice #LeetCode #SoftwareEngineering #ProblemSolving #TechJourney

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories