Solved LeetCode 2859 with Java and Bit Manipulation

💡 LeetCode 2859 – Sum of Values at Indices With K Set Bits 💡 Today, I solved LeetCode Problem #2859, a clever mix of bit manipulation and array traversal that emphasizes how understanding binary representations can simplify computational logic. ⚙️ 🧩 Problem Overview: You are given a list of integers nums and an integer k. Your task is to find the sum of all elements at indices whose binary representation contains exactly k set bits (1s). 👉 Examples: Input → nums = [5,10,1,5,2], k = 1 → Output → 13 (Indices 1 and 2 have one set bit → nums[1] + nums[2] = 10 + 3) 💡 Approach: 1️⃣ Loop through all indices in the list. 2️⃣ Use Integer.bitCount(i) to count the number of set bits in the binary representation of each index. 3️⃣ If it equals k, add nums[i] to the sum. 4️⃣ Return the final total. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Linear scan of the list. ✅ Space Complexity: O(1) — Constant space usage. ✨ Key Takeaways: Strengthened understanding of bit-level operations using Java’s built-in methods. Reinforced how binary logic often leads to elegant and concise solutions. Demonstrated the power of combining mathematical reasoning with simple iteration. 🌱 Reflection: Bit manipulation is one of the most underrated yet powerful tools in problem-solving. This problem shows how thinking in binary can make complex conditions crystal clear — and the solution clean, efficient, and elegant. 🚀 #LeetCode #2859 #Java #BitManipulation #DSA #ProblemSolving #CodingJourney #AlgorithmicThinking #CleanCode #DailyPractice #ConsistencyIsKey

  • text

To view or add a comment, sign in

Explore content categories