100 Days of Code: Bit Manipulation and Dynamic Programming Challenge

🚀 #100DaysOfCode – Day 10 | DSA Practice Continuing my 100 Days Data Structures and Algorithms challenge, today I worked on a problem based on bit manipulation and dynamic programming. 📌 Problem: Counting Bits Given an integer n, return an array ans where each index i (0 ≤ i ≤ n) contains the number of 1’s in the binary representation of i. Example: Input: n = 5 Output → [0,1,1,2,1,2] 🧠 Approach / Logic: 1️⃣ Initialize a result array of size n + 1. 2️⃣ Start from i = 1 and go till n. 3️⃣ For each number i, divide it by 2 → i / 2 (this removes the last bit). 4️⃣ Check if the last bit is 1 using i % 2. 5️⃣ Use the relation: ans[i] = ans[i / 2] + (i % 2) 6️⃣ This helps reuse previously computed results → making it efficient. 📊 Time Complexity: O(n) 📦 Space Complexity: O(n) 🎯 Key Learning: This problem shows how bit manipulation + dynamic programming can optimize solutions from brute force to linear time. Consistency is the key to growth. Let’s keep improving step by step! 💪 #100DaysOfCode #DSA #CodingJourney #ProblemSolving #CPP #LearningInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories