🚀 Coding Practice — Check if a Number Has Alternating Bits (Bit Manipulation) 🔄✨Alternating Bits ⚡ The Binary Seesaw 🔥🔥🔥 Beats 100% Today I worked on a neat bit-manipulation problem: determine whether a number’s binary representation contains alternating bits — meaning no two adjacent bits are the same. Examples: ✅ Valid → 10101, 0101 ❌ Invalid → 110, 1001 🧠 Intuition Think of binary digits like stepping stones that must alternate colors — ⚫⚪⚫⚪ — at every step. If you ever step on two same-colored stones in a row, the pattern breaks. Instead of converting the number to a binary string, we directly inspect each bit using bitwise operations — which is faster and more memory-efficient. Core idea: Extract the last bit using n & 1 Shift right using n >> 1 Compare with the previous bit If equal → not alternating 🛠️ Approach (Step-by-Step) 1️⃣ Capture the least significant bit (LSB) using n & 1 2️⃣ Right shift the number to move to the next bit 3️⃣ Loop while the number is not zero: Store previous bit Extract current bit If both are equal → return False Otherwise continue shifting 4️⃣ If loop completes → all bits alternated → return True 💻 Python Code class Solution: def hasAlternatingBits(self, n: int) -> bool: curr = n & 1 n >>= 1 while n: prev = curr curr = n & 1 if curr == prev: return False n >>= 1 return True 📊 Complexity Analysis ✅ Time Complexity: O(log n) We check each bit once. A number has about log₂(n) bits. ✅ Space Complexity: O(1) Only constant variables are used. ✨ Bit manipulation problems like this are great for strengthening low-level logic and understanding how numbers are stored internally. Small problems — big thinking benefits. #Python #CodingPractice #BitManipulation #DSA #ProblemSolving #InterviewPrep #LearnToCode #TechLearning
Check if Number Has Alternating Binary Bits
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
-
-
🚀 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
To view or add a comment, sign in
-
-
Day 58 of My Daily Coding Challenge 1680. Concatenation of Consecutive Binary Numbers Today’s problem pushed me to think beyond the obvious approach. Problem Summary: Given an integer n, we need to concatenate the binary representations of numbers from 1 to n, then return the decimal value of that huge binary number modulo 109+710^9 + 7109+7. At first glance, it feels like a simple string problem — just convert numbers to binary and join them. But with constraints up to 10510^5105, that approach becomes inefficient. Key Insight: Instead of building the binary string: Use bitwise left shift to simulate binary concatenation. Increase bit length whenever the number becomes a power of 2. Apply modulo at each step to prevent overflow. This problem helped me strengthen: ✔ Understanding of bit manipulation ✔ Mathematical thinking over brute force ✔ Optimizing solutions for large constraints ✔ Writing clean and efficient Python code What I loved most about this problem is how it transforms a “string-based” question into a “bitwise math” solution. Every day I realize that problem solving is less about syntax and more about pattern recognition and logical thinking. #Day58 LeetCode Algorithms Software Pvt Ltd #BitManipulation Python #ProblemSolving Journey Coding
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
-
Writing code that works is the first step, but writing code that doesn't break when users make mistakes is what separates a beginner from a professional. This week, I focused on Exception Handling to make my applications "bulletproof." Instead of letting a program crash due to invalid inputs, I've implemented a robust "Try-Except" flow. Key takeaways from this stage: ✅ Defensive Programming: Anticipating potential runtime errors before they happen. ✅ The Try-Except-Pass Pattern: Creating clean, non-intrusive loops that guide users toward the correct input without breaking the flow. ✅ Modular Validation: Abstracting data validation into reusable functions to keep the main logic clean and readable. I refactored my previous projects into a more resilient structure, ensuring that only valid numeric data reaches the calculation engine. It’s all about creating a seamless user experience, even when things go wrong. Next stop: Exploring Python Libraries to extend my toolkit! 🚀 #Python #SoftwareDevelopment #Coding #CleanCode #ErrorHandling #VibeCoders #ProgrammingLogic
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
-
-
Debugging is just high-stakes problem solving. They say code is 10% writing and 90% debugging. But the best debugging doesn't just fix a "bug"—it uncovers a better way to think about the problem. 💡 When I started this LeetCode challenge, I looked for the most obvious path. But after a few rounds of testing and refinement, I realized that the "cleanest" code is the one where bugs have nowhere to hide. By moving from complex loops to Bit Manipulation, I reduced the surface area for errors and achieved a perfect 0ms runtime. 🚀 Debugging isn't a chore; it's the process of distilling logic until only the truth (and a 100% beat rate) remains. #Debugging #SoftwareEngineering #ProblemSolving #Python #LeetCode #CleanCode #DeveloperJourney #snsinstitutions #snsdesignthinkers #snsdesignthinking
To view or add a comment, sign in
-
-
AI coding agents are evaluated almost entirely on Python. SWE-bench and its variants have driven enormous progress — but they cover a narrow slice of real software engineering. The world's codebases span dozens of languages, and most production code isn't Python. arXiv:2602.23866 introduces SWE-rebench V2 — an automated pipeline for harvesting executable software engineering tasks at unprecedented scale. What it provides: → 32,000+ tasks spanning 20 programming languages → 3,600+ real repositories → 120,000+ additional tasks with full metadata for RL training → Pre-built Docker images for reproducible execution per task The pipeline is fully automated — it identifies GitHub issues with linked PRs, extracts test deltas, and builds isolated execution environments. No human annotation required. Why this matters: → Existing SWE-bench variants are effectively Python-only → Coding agents need diverse language exposure to generalize → 32K executable tasks with Docker environments = ready for RL training → Language diversity mirrors real deployment scenarios SWE-bench was a watershed moment for coding agents. SWE-rebench V2 extends that benchmark surface to the full programming landscape. #AIAgents #SoftwareEngineering #MachineLearning #LLM #ResearchPaper
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
-
-
I built a simple Number Guessing Game… and it changed the way I think. When I started learning Python, I thought programming was about writing complex code. Big screens. Advanced systems. “Serious” projects. But staring at a blank editor? That’s where the doubt kicks in. “Can I really do this?” Turns out programming isn’t about complexity. It’s about clarity. My small Number Guessing Game taught me more than I expected. • Python isn’t just beginner-friendly — it trains your thinking. • Conditionals and loops aren’t just syntax — they shape logic. • Debugging isn’t failure — it’s feedback. Here’s the bold truth: Small projects build real confidence faster than big dreams ever will. Every error forced me to think better. Every fix made me sharper. And that shift? That’s powerful. If you’re starting out in tech and feel like your projects are “too small” keep going. We all start somewhere.
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