🚀 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
Counting Prime Set Bits in Binary Representation
More Relevant Posts
-
🚀 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
-
-
200 LeetCode Problems I recently crossed the milestone of solving 200 problems on LeetCode, all implemented in Python. Working through Easy, Medium, and Hard challenges has helped me strengthen my coding skills, improve problem‑solving strategies, and gain confidence across different areas. Some of the key lessons from this journey include: 1. Using Python tools like Counter, defaultdict, and cmp_to_key effectively. 2. Implementing permutation problems and generating powersets with itertools.combinations. 3. Handling 32‑bit integer range constraints when required. 4. Applying binary search in creative ways — from rotated arrays to math problems like sum of squares. 5. Elegant tricks such as matrix transpose in one line with zip(*matrix). 6. Tackling 3Sum/4Sum using two‑pointer techniques and duplicate handling. 7. Leveraging prefix sums for problems like Push Dominoes and subarray challenges. 8. Using float('inf') and float('-inf') for boundary conditions. 9. Managing time and space complexity trade‑offs more effectively. Through these 200 problems, I’ve worked across: 1. Math & Number Theory (powers, squares, integer ranges) 2. Strings (palindromes, anagrams, permutations, custom sorting) 3. Arrays & Searching (binary search, rotated arrays, prefix sums, subarrays) 4. Hashing & Frequency (Counter, defaultdict, frequency maps) 5. Design & Implementation (HashMap, HashSet, Randomized set, TinyURL) 6. Classic Interview Problems (3Sum, 4Sum, Kth largest, Trapping Rain Water, Median of Two Sorted Arrays) This milestone is a reminder that consistent practice builds intuition, resilience, and confidence. Along the way, I’ve analyzed my progress and realized that I need to put more focus on prefix sums and subarray problems to strengthen my skills further. #LeetCode #PythonProgramming #ProblemSolving #Algorithms #DataStructures #CodingJourney #InterviewPreparation #ContinuousLearning #SoftwareEngineering #Learning #LogicalThinking
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
-
-
Most people think AI agents are complex, mysterious systems. They're not. An agent is a thermostat. It reads a sensor (your prompt). It compares to a target (the task). It triggers an action (calls a tool). Then it waits and repeats. That's it. That's the architecture behind Claude Code, Cursor, and Copilot. The difference between understanding this and not? When it breaks, you know exactly which line caused it. We wrote a book that teaches you to build one from scratch in 750 lines of Python. No frameworks. No magic. Follow this page for more posts like this. https://lnkd.in/gWdFWM4g #AIAgents #Python #SoftwareEngineering #LLM
To view or add a comment, sign in
-
This metaphor changed how I explain AI agents to non-technical people. Once you say "thermostat," the mystique evaporates — and what's left is just engineering. That's why I wrote the book.
Most people think AI agents are complex, mysterious systems. They're not. An agent is a thermostat. It reads a sensor (your prompt). It compares to a target (the task). It triggers an action (calls a tool). Then it waits and repeats. That's it. That's the architecture behind Claude Code, Cursor, and Copilot. The difference between understanding this and not? When it breaks, you know exactly which line caused it. We wrote a book that teaches you to build one from scratch in 750 lines of Python. No frameworks. No magic. Follow this page for more posts like this. https://lnkd.in/gWdFWM4g #AIAgents #Python #SoftwareEngineering #LLM
To view or add a comment, sign in
-
Utilizing the Math Module for Square Roots and Factorials Modules in Python are essential for code organization and reusability, and the `math` module serves as a built-in resource that provides a variety of mathematical functions. When you import a module, you bring a toolkit of pre-defined functions, constants, and classes into your workspace, simplifying complex tasks without needing to rewrite code. In the example above, we leverage the `math` module to perform two mathematical operations: calculating the square root and finding the factorial. The `math.sqrt()` function efficiently computes the square root of a number, while `math.factorial()` finds the factorial of a given integer. These built-in functions illustrate how you can significantly simplify coding tasks by utilizing existing libraries. Importing a module is straightforward with the `import` keyword, and functions within the module are accessed via dot notation. This allows for easy calls like `math.sqrt()` and `math.factorial()` after importing `math`. Understanding this concept encourages the use of Python's built-in capabilities, enhancing both maintainability and readability of your code. Additionally, you can create your own modules. This feature lets you encapsulate related functions and classes, making your code reusable across different projects. Writing modular code not only keeps your main script clean but also facilitates collaboration, allowing others to navigate your code structure more easily. Quick challenge: What would you need to change in the code if you wanted to find the natural logarithm instead? #WhatImReadingToday #Python #PythonProgramming #Modules #CodeReuse #Programming
To view or add a comment, sign in
-
-
A hands-on collection of real-world implementations to build LLM-powered applications using Python, LangChain, and Hugging Face. What’s inside: • RAG pipelines (Chroma / FAISS) • Custom/opensource LLM integrations • Memory & prompt engineering • Autonomous agents (ReAct style) Built with 2026 best practices to help you get started with production-ready #AI apps. #LLM #LangChain #HuggingFace #Python #MachineLearning #RAG #GenerativeAI https://lnkd.in/gqQ5sZVc
To view or add a comment, sign in
-
🚀 𝗗𝗮𝘆 𝟯 𝗼𝗳 𝗠𝘆 𝗣𝘆𝘁𝗵𝗼𝗻 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 Today I focused on understanding some of the core building blocks of programming in Python. 𝗧𝗼𝗱𝗮𝘆’𝘀 𝗧𝗼𝗽𝗶𝗰𝘀: • While Loop – Learned how to execute code repeatedly while a condition remains true. • For Loop – Used to iterate through ranges, lists, and sequences efficiently. • Functions – Understood how to organize code into reusable blocks. • Recursion – Explored how a function can call itself to solve problems step-by-step. 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝗱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺𝘀: ✔ Printed star patterns using loops ✔ Built number triangle patterns ✔ Used recursion to print list elements ✔ Practiced loop logic with different pattern problems Example of a recursion concept I practiced: 𝘥𝘦𝘧 𝘱𝘳𝘪𝘯𝘵_𝘭𝘪𝘴𝘵(𝘢𝘳𝘳, 𝘪𝘥𝘹=0): 𝘪𝘧 𝘪𝘥𝘹 == 𝘭𝘦𝘯(𝘢𝘳𝘳): 𝘳𝘦𝘵𝘶𝘳𝘯 𝘱𝘳𝘪𝘯𝘵(𝘢𝘳𝘳[𝘪𝘥𝘹]) 𝘱𝘳𝘪𝘯𝘵_𝘭𝘪𝘴𝘵(𝘢𝘳𝘳, 𝘪𝘥𝘹 + 1) This helped me understand how recursion works internally using the call stack. 💡 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠 𝐓𝐨𝐝𝐚𝐲: Loops control repetition, functions organize logic, and recursion solves problems by breaking them into smaller parts. Every day I’m improving my problem-solving ability and programming mindset. On to 𝗗𝗮𝘆 𝟰 𝗼𝗳 𝗣𝘆𝘁𝗵𝗼𝗻 tomorrow. #Python #LearningInPublic #Programming #DeveloperJourney #100DaysOfCode
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
-
Today’s practice was focused on String and List Manipulation using Slicing. This session helped me understand how powerful slicing is in Python and how it can simplify many problems without using loops. Programs practiced today include: 🔹 Reverse a given string using slicing 🔹 Print every alternate character from a string 🔹 Extract the middle three characters from a string 🔹 Reverse a list of integers using slicing (without loops or built-in reverse functions) 🔹 Remove the first and last characters from a string using slicing Key learnings from today’s session: • Understanding slicing syntax: start : stop : step • Using negative indexing for reversing sequences • How [::-1] works internally • Extracting specific portions of strings efficiently • Writing clean and shorter code without unnecessary loops • Strengthening fundamentals in string and list operations Today’s practice showed me how Python provides elegant solutions for common problems. Instead of writing long logic with loops, slicing makes the code simpler and more readable. Step by step, improving both logic and code efficiency. Grateful for the continuous guidance and support from the #10kcoders team. #Day32 #Python #StringManipulation #ListOperations #Slicing #LogicBuilding #ProgrammingJourney #Consistency
To view or add a comment, sign in
-
More from this author
Explore related topics
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