🚀 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
Count Binary Substrings in Python
More Relevant Posts
-
🚀 Coding Practice — Prime Number of Set Bits (Bit Manipulation) Today I solved an interesting bit manipulation problem: 👉 Given two integers left and right, count how many numbers in the range [left, right] have a prime number of set bits in their binary representation. 🧠 Problem Understanding A set bit means a 1 in binary representation. Example: 21 → 10101 → 3 set bits We must: Convert each number in range [left, right] to binary Count number of 1s Check if that count is prime Return total count 🔍 Key Insight (Optimization Trick) Given constraint: 1 ≤ left ≤ right ≤ 10^6 0 ≤ right - left ≤ 10^4 Maximum number of bits required for 10^6: log₂(10^6) ≈ 20 So maximum possible set bits = 20 That means we only need to check primes up to 20: {2, 3, 5, 7, 11, 13, 17, 19} ⚡ Instead of checking prime every time, we store these in a set for O(1) lookup. ✅ Optimized Python Solution class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: # Prime numbers up to 20 (maximum possible set bits) primes = {2, 3, 5, 7, 11, 13, 17, 19} count = 0 for num in range(left, right + 1): set_bits = num.bit_count() # Fast built-in method if set_bits in primes: count += 1 return count 🔎 Example 1 Input: left = 6, right = 10 NumberBinarySet BitsPrime?61102✅71113✅810001❌910012✅1010102✅ ✔ Output = 4 ⏱ Complexity Analysis Time Complexity: O(N) where N = right - left (max 10^4) Space Complexity: O(1) Very efficient and well within constraints. #Python #CodingPractice #BitManipulation #ProblemSolving #DataStructures #InterviewPreparation #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 48 of #100DaysOfCode I recently tackled an interesting coding problem: “Given a binary number as a string, find the number of steps to reduce it to 1. If even, divide by 2; if odd, add 1.” For example: Input: "1101" → Output: 6 Input: "10" → Output: 1 Input: "1" → Output: 0 Instead of converting the binary to decimal, I simulated the steps directly on the binary string, which makes it efficient even for very long numbers. Here’s the Python solution I implemented: def numSteps(s: str) -> int: steps = 0 s = list(s) while len(s) > 1: if s[-1] == '0': s.pop() else: i = len(s) - 1 while i >= 0 and s[i] == '1': s[i] = '0' i -= 1 if i >= 0: s[i] = '1' else: s.insert(0, '1') steps += 1 return steps print(numSteps("1101")) # 6 💡 Key Takeaways: You can work directly with binary strings instead of converting them to integers. Simulating operations step by step is often more memory-efficient. This approach works even for very long binary strings (up to 500 bits in this problem). Coding challenges like this are a great way to sharpen algorithmic thinking! 🧠 #Python #CodingChallenge #BinaryNumbers #ProblemSolving #LeetCode #Algorithms
To view or add a comment, sign in
-
-
🚀 LeetCode Practice 📌 Problem: Number of Steps to Reduce a Number in Binary Representation to One 🔗 LeetCode Problem #1404 🧠 Problem Statement Given a binary string s, return the number of steps required to reduce it to "1" using: ✅ If the number is even → divide it by 2 ✅ If the number is odd → add 1 It is guaranteed that we can always reach "1". 🔎 Example Input: s = "1101" Output: 6 Explanation: 13 (1101) → +1 → 14 14 → /2 → 7 7 → +1 → 8 8 → /2 → 4 4 → /2 → 2 2 → /2 → 1 💡 Key Insight The length of s can be up to 500 bits, so converting directly to an integer might not be ideal in some languages. Instead, we: Traverse from right to left Simulate division and addition Maintain a carry variable Count operations efficiently ⚡ Optimized Approach (Greedy + Carry Handling) 🔥 Core Observations If last bit is '0' → number is even → 1 step (divide) If last bit is '1' → number is odd → 2 steps (add 1 + divide) Handle carry propagation carefully 🧑💻 Python Implementation (O(n) Time | O(1) Space) class Solution: def numSteps(self, s: str) -> int: steps = 0 carry = 0 # Traverse from right to left (ignore MSB) for i in range(len(s) - 1, 0, -1): bit = int(s[i]) # If bit + carry == 1 → odd if bit + carry == 1: steps += 2 carry = 1 else: steps += 1 return steps + carry 📊 Complexity Analysis ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Where n is the length of the binary string. #LeetCode #ProblemSolving #Python #DSA #CodingInterview #BitManipulation #TechGrowth
To view or add a comment, sign in
-
-
𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐏𝐲𝐭𝐡𝐨𝐧 𝐋𝐨𝐨𝐩𝐬: 𝐓𝐡𝐞 𝐎𝐧𝐥𝐲 𝐓𝐰𝐨 𝐓𝐡𝐚𝐭 𝐌𝐚𝐭𝐭𝐞𝐫. 🔄 𝐖𝐡𝐞𝐧 writing Python, iteration is a core part of our daily workflow. But despite all the advanced techniques out there, Python technically only has two real loop statements: the for loop and the while loop[cite: 289, 290, 291]. Everything else we use is simply a pattern, a control feature, or a syntax shortcut[cite: 292]. 𝐔𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 when to use which is the key to writing clean and efficient code. The for loop is best when you are working with known collections like lists, strings, or dictionaries[cite: 297, 298]. The while loop is your go-to when the number of repeats is unknown and depends on a specific condition remaining True[cite: 305, 306]. 𝐊𝐞𝐲 𝐂𝐨𝐧𝐜𝐞𝐩𝐭𝐬 𝐭𝐨 𝐊𝐧𝐨𝐰:- • 𝐋𝐨𝐨𝐩 𝐂𝐨𝐧𝐭𝐫𝐨𝐥𝐬: Use break to stop a loop immediately [cite: 329, 330], or continue to skip the current iteration and move to the next[cite: 331, 332]. • 𝐂𝐨𝐦𝐩𝐫𝐞𝐡𝐞𝐧𝐬𝐢𝐨𝐧𝐬: List, set, and dictionary comprehensions are compact, Pythonic iteration shortcuts[cite: 342, 343, 344]. They are not new loops, just cleaner ways to write them. • 𝐓𝐡𝐞 𝐞𝐥𝐬𝐞 𝐂𝐥𝐚𝐮𝐬𝐞: A unique Python feature where an else block runs only if the loop ends naturally without hitting a break statement[cite: 336, 337, 338]. Conclusion:- 𝐔𝐥𝐭𝐢𝐦𝐚𝐭𝐞𝐥𝐲, becoming a strong engineer means you must master logic, not just syntax[cite: 352]. By deeply understanding these two fundamental loops, you can build any complex iteration pattern required for your system. Special thanks to my mentor Mian Ahmad Basit for the continued guidance. #MuhammadAbdullahWaseem #Nexskill #PythonProgramming #SoftwareEngineering #Pakistan #Ramadan
To view or add a comment, sign in
-
-
Day 13 – Practice with Recursion, Loops, and String Logic in Python Day 13 was all about hands-on problem solving. I focused on strengthening my logical thinking by implementing common programming problems using functions, loops, recursion, and strings. What I practiced today: Recursion Concepts: Calculated the sum of N natural numbers using recursion Example: input = 5 → output = 15 Understood how recursive calls work and when to stop using base conditions Loop-Based Logic (Without Recursion): Printed N Fibonacci numbers using loops Learned why loops are more memory-efficient than recursion in some cases String Processing Problems: Found the frequency of each character in a string using dictionaries Counted occurrences of characters without using built-in methods Compared two strings and printed common characters Avoided duplicate counting using a checked/reference string Pattern & Combination Problems: Printed all possible character pairs from a given string Example: "abc" → ab, ac, bb, bc, ca, cb, cc Practiced nested loops to generate combinations List & String Manipulation: Reversed each string inside a list without using slicing Converted: ["apple", "banana", "orange", "mango", "grapes"] into reversed word format Key Takeaways: Improved understanding of nested loops and condition checks Learned how to avoid repeated computations Practiced writing logic without relying on shortcuts or built-in functions Strengthened confidence in solving interview-style problems Consistent practice like this is helping me think more clearly about how code actually works step by step. #Python #PythonPractice #ProblemSolving #Recursion #Loops #StringManipulation #LogicalThinking #DailyLearning #CodingPractice #ComputerScience
To view or add a comment, sign in
-
Why I’m Trading "Drag-and-Drop" for Python in Optimization Workflows =================================== In simulation-driven design, the real bottleneck isn't usually the solver—it’s the workflow. Tools like iSight are undeniably powerful. They offer a structured environment and a "plug-and-play" feel for DOE and optimization that can be a lifesaver for standard CAE tasks. But, as many of us have found, that convenience often comes with a "walled garden" tax. The Friction Points ----------------------- Proprietary platforms require a specific kind of "tool-fluency." When you hit a wall, you aren't just solving an engineering problem; you're debugging a closed ecosystem. Limited documentation and a smaller user base mean that troubleshooting often feels like a solo mission. Why Python Wins for Me ------------------------------- This is where Python transforms the experience from "configuring a tool" to "building a solution." Using libraries like SciPy, Optuna, and PyDOE offers a level of granularity that GUI-based tools just can't match. * Version Control: You can actually git commit a script; try doing that effectively with a proprietary project file. * Community Power: If you’re stuck, a solution is usually one Stack Overflow thread or GitHub Issue away. * Future-Proofing: It’s much easier to bridge your optimization results into an ML framework or a custom dashboard when you're already in a coding environment. For teams that live in scripting and automation, Python isn't just an alternative—it’s a faster, more scalable, and frankly, more enjoyable way to work. It turns a rigid process into a creative one. #CAE #CFD #DesignOptimization #EngineeringSimulation #Python #SimulationDrivenDesign #EngineeringAutomation #MachineLearning #DigitalEngineering
To view or add a comment, sign in
-
-
In plain English, "and" and "or" are just connective words. In Python, they are strict gatekeepers. 🧐 ⠀ Confusing them is the easiest way to break the logic of your application. ⠀ Let's look at a real-world example: Going to the cinema. 🍿 ⠀ 🎬 The "Flexible" Approach (OR): Imagine regular entry to a movie. You write: `if has_paper_ticket OR has_digital_app:` ⠀ The `or` operator is chill. It opens the door if *either* condition is met. Did you forget your paper ticket but have your phone? No problem. You're in. ⠀ 🔞 The "Strict" Approach (AND): Now imagine entry to an age-restricted screening (18+). You write: `if has_ticket AND is_over_18:` ⠀ The `and` operator is the strict manager. It demands *both* requirements be met simultaneously. Have a ticket but forgot your ID? You aren't getting in. ⠀ Logical operators aren't just syntax; they define the rules of your digital world. ⠀ Don't accidentally lock your users out (or let the wrong ones in) because you chose the wrong conjunction. ⠀ We turn boring Python documentation into a friendly, 3-minute daily habit. ☕ ⠀ 👇 Subscribe to the website for free: https://lnkd.in/ducXvs-y ⠀ #Python #Logic #CodingTips #SoftwareDevelopment #LearnToCode #PyDaily
To view or add a comment, sign in
-
-
Have you ever noticed how much of your code is actually just working with text? The more I program in Python, the more I respect how powerful string handling really is. Strings may look simple, but they are one of the most essential data types in real-world applications. One key lesson I learned early is that text value is immutable. That means when I “change” a string, I’m actually creating an updated copy, not modifying the original text.If I forget to assign the result to cleaned text or formatted line, nothing is saved. Methods like replace(), upper(), lower(), title(), and capitalize() help me quickly transform raw_input into polished_output. For example, I can take greeting_line and turn it into greeting_line.upper() for emphasis, while the source remains untouched. When handling user_input or file_content, I often rely on strip(), lstrip(), and rstrip() to remove unwanted spaces or noisy_characters. But I use them carefully, because removing the wrong symbols can turn meaningful data into an empty string. That small detail can break validation logic in seconds. My advice to developers is simple. Always store transformation results in a new variable like normalized_text instead of reusing vague names like s or temp. Validate input_length before and after cleaning. And remember that chaining methods like raw_text.strip().lower() is powerful, but readability still matters. Clean text processing creates clean software architecture. #evgenprolife #Python #Programming #CodeQuality #SoftwareDevelopment #LearnToCode #BackendDevelopment #CleanCode #PythonTips #DeveloperLife #CodingJourney
To view or add a comment, sign in
-
-
**Dangerous Python** **Artifact #2 -> a function whose AST is rewritten before execution** Most programmers think code lives in two moments: first, it is written then, it runs Python allows a third. A program can inspect its own structure before that structure becomes execution. That structure is the AST. The Abstract Syntax Tree. Not the source text. Not yet the bytecode. The internal shape of the program. And yes, it can be modified. Which means code may begin in one form and execute in another. Same name. Same function. Different structure. This is deeper than runtime mutation. In Artifact #1, the function changed its engine while running. In Artifact #2, we go lower. We change the syntactic skeleton before the function fully comes into existence. That is what makes AST rewriting so powerful and so dangerous. Because now a program is no longer just something that runs. It can read itself. Transform itself. Recompile itself. Return as something else. Useful in compilers, linters, instrumentation, symbolic systems, and code generation. But in normal application code, this feels less like engineering and more like opening the back door of the language. Artifact #1 changed the engine. Artifact #2 changes the blueprint. Example below. PYTHON ALLOWS SOMETHING EVEN STRANGER: A FUNCTION MAY ARRIVE IN EXECUTION WEARING THE SAME NAME, WHILE CARRYING A DIFFERENT STRUCTURE THAN THE ONE THAT WAS WRITTEN. NOT PATCHED AFTERWARD. REWRITTEN BEFORE BIRTH. #Python #Metaprogramming #AST #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
Nobody tells you this when you start coding. You can write code that works. And still have absolutely no idea what it is doing. I was that person. I wrote loops like I was placing furniture in a room blindfolded. Technically something landed somewhere. Practically, the couch was on the ceiling. The real shift happened when I stopped asking "does this run" and started asking "what is Python actually doing right now, line by line." Turns out there is an entire conversation happening inside your machine that nobody teaches you. Python checks every condition like a bouncer at a club. True gets in. False does not. Everything else is secretly converted into one of those two before the decision is made. A for loop is not magic. It is an assembly line. One item at a time. Same action. Repeat until the belt is empty. A while loop is a watchman who checks the gate every single second. The moment the answer becomes No, he locks up and goes home. Once you see the mechanics, something clicks. You stop guessing why your code broke. You already know. Because you understand the consequences of every line before you write it. Building logic is not about knowing syntax. Syntax you can Google in 10 seconds. Logic is about knowing what question your code is asking. And knowing what answer it expects back. Most people learn to type code. Very few learn to think in it. The ones who think in it are the ones who debug in 2 minutes while everyone else is on Stack Overflow for 2 hours. Learn the BTS. Not just the output. #Python #Coding #DataAnalytics #CareerGrowth #LearnToCode #100DaysOfCode #PythonDeveloper #TechCareers
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development