💡 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
Solved LeetCode 2859 with Java and Bit Manipulation
More Relevant Posts
-
💡 LeetCode 3370 – Smallest Number With All Set Bits Greater Than or Equal to n 💡 Today, I solved LeetCode Problem #3370, a concise yet insightful bit manipulation problem that sharpened my understanding of binary operations and number construction using bitwise logic in Java. ⚙️💻 🧩 Problem Overview: Given an integer n, the task is to find the smallest number that is greater than or equal to n and has all bits set to 1 in its binary form. 👉 Examples: Input → n = 5 (binary 101) → Output → 7 (binary 111) Input → n = 10 (binary 1010) → Output → 15 (binary 1111) 💡 Approach: 1️⃣ Initialize x = 1 (binary 1). 2️⃣ Continuously left-shift and OR with 1 → x = (x << 1) | 1, until x becomes ≥ n. 3️⃣ Return x as the final result — a number with all bits set to 1 that satisfies the condition. ⚙️ Complexity Analysis: ✅ Time Complexity: O(log n) — Each iteration handles one bit of n. ✅ Space Complexity: O(1) — Uses only constant extra space. ✨ Key Takeaways: Reinforced understanding of bitwise shift (<<) and bitwise OR (|) operators. Demonstrated how to efficiently generate numbers following binary patterns. Proved that elegant logic often lies in simplicity — especially in bit manipulation problems. 🌱 Reflection: This problem showcases how bit-level operations can simplify what might seem like mathematical complexity. Mastering these techniques is essential for building deeper intuition in algorithms and optimization. 🚀 #LeetCode #3370 #Java #BitManipulation #BinaryLogic #DSA #ProblemSolving #AlgorithmicThinking #CodingJourney #CleanCode #ConsistencyIsKey
To view or add a comment, sign in
-
-
📌 Day 8/100 - Search Insert Position (LeetCode 35) 🔹 Problem: Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be inserted in order. 🔹 Approach: I used a binary search approach for efficiency 🔍 1️⃣ Start with two pointers — low and high. 2️⃣ Find the mid index and compare nums[mid] with the target. 3️⃣ If target equals nums[mid], return mid. 4️⃣ If target is smaller, move the high pointer left. 5️⃣ If target is greater, move the low pointer right. 6️⃣ When the loop ends, low gives the correct insert position. 🔹 Key Learning: Binary Search saves time — reducing O(n) to O(log n)! Understanding the condition when to move left/right is key. Even simple problems sharpen logical precision and boundary handling. Each problem strengthens the logic muscle 🧠 — one step closer to mastering algorithms! 💪 #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #LearnByDoing
To view or add a comment, sign in
-
-
✅ Just solved LeetCode #654 — Maximum Binary Tree 📘 Problem: Given an integer array without duplicates, the task is to build a maximum binary tree. The construction rules are: 1️⃣ The root is the maximum element in the array. 2️⃣ The left subtree is built recursively from elements to the left of the maximum. 3️⃣ The right subtree is built recursively from elements to the right of the maximum. Example: Input → [3,2,1,6,0,5] Output → [6,3,5,null,2,0,null,null,1] 🧠 My Approach: I solved this problem using a recursive divide-and-conquer approach. 1️⃣ Find the index of the maximum element in the given range — this becomes the root. 2️⃣ Recursively build the left subtree from the subarray before the maximum element. 3️⃣ Recursively build the right subtree from the subarray after the maximum element. 💡 What I Learned: ✅ How recursion naturally fits into tree construction problems ✅ The concept of divide and conquer applied to array-based tree building ✅ How to translate problem definitions into direct recursive structure #LeetCode #Java #DSA #BinaryTree #CodingUpdate #LearningByDoing
To view or add a comment, sign in
-
-
🚀 Day 52 of #100DaysOfCode 🚀 Today I solved LeetCode Problem #389 – Find the Difference 🧩 This problem is a great example of using ASCII value manipulation to solve what seems like a string comparison challenge. 💡 Key Learnings: Strengthened understanding of character encoding (ASCII values) and how they can simplify logic. Learned how summing character values can help detect differences efficiently without extra data structures. Reinforced the value of O(n) solutions for string-based problems. 💻 Language: Java ⚡ Runtime: 1 ms — Beats 99.32% 🚀 📉 Memory: 41.9 MB — Beats 65.84% 🧠 Approach: 1️⃣ Convert both strings to character arrays. 2️⃣ Compute the sum of ASCII values of both. 3️⃣ The difference between sums gives the ASCII value of the extra character in t. Simple, elegant, and efficient! ⚙️ Sometimes, a clever use of ASCII arithmetic can replace complex logic — efficiency lies in simplicity. #100DaysOfCode #LeetCode #Java #ProblemSolving #CodingChallenge #Algorithms #DataStructures #SoftwareDevelopment #LearningEveryday #CleanCode
To view or add a comment, sign in
-
-
🗓 Day 8/ 100 – #100DaysOfLeetCode 📌 Problem 3234: Count the Number of Substrings With Dominant Ones A substring is said to have dominant ones if: 👉 #1s ≥ (#0s)² The task is to count how many substrings in the binary string satisfy this condition. 🧠 My Approach: 🔹 Iterated through substrings while maintaining counts of zeros and ones. 🔹 Used the condition ones ≥ zeros² to determine whether a substring is valid. 🔹 Applied early stopping when the zero count became too large, since the quadratic requirement makes dominance increasingly difficult to achieve. 🔹 This pruning significantly reduced unnecessary checks and improved the overall efficiency. ⏱ Time & Space Complexity Time Complexity: O(n · √n) Because for each starting index, we only explore substrings until the zero count reaches ~√n (beyond which zeros² becomes too large to satisfy). This is a major improvement over the brute-force O(n²). Space Complexity: O(1) Only uses a few counters (ones, zeros, indices). 💡 Key Learning: This problem beautifully shows how mathematical constraints can simplify substring evaluation. Recognizing that zeros affect the condition quadratically helped guide a smarter pruning strategy, turning an expensive brute-force check into something efficient and elegant. #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
To view or add a comment, sign in
-
-
🚀 Day 146 / 180 of #180DaysOfCode ✅ Today’s Highlight: Revisited LeetCode 3234 — “Count the Number of Substrings With Dominant Ones.” 🧩 Problem Summary: Given a binary string s, the task is to count how many of its substrings have dominant ones. A substring is considered dominant if: number of 1s ≥ (number of 0s)² This creates an interesting balance check between zeros and ones, pushing you to think about substring ranges, prefix behavior, and efficient counting techniques. 💡 Core Takeaways: Great exercise in string analysis and prefix-based reasoning Highlights how mathematical conditions influence algorithm design Reinforces handling frequency relationships inside a sliding or expanding window Efficient counting becomes essential due to potential O(n²) substrings 💻 Tech Stack: Java ⏱ Runtime: 115 ms (Beats 84.11%) 💾 Memory: 47 MB 🧠 Learnings: Strengthened understanding of substring behavior under unique constraints Refined thinking around optimizing brute-force patterns A good reminder of how theoretical conditions (like squaring zeros) change practical implementation choices 📈 Progress: Today’s problem significantly improved my intuition around constraint-based substring evaluation—valuable for more advanced algorithmic challenges ahead. #LeetCode #Java #Algorithms #SubstringProblems #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #180DaysOfCode #LogicBuilding #LearningEveryday
To view or add a comment, sign in
-
-
🚀 Day 60 of #100DaysOfCode 🚀 Today, I solved LeetCode Problem #137 – Single Number II 🧩 📘 Problem Statement: Given an integer array where every element appears three times except for one that appears exactly once, find that single element and return it. The challenge: solve it with O(n) time and O(1) space complexity. 💻 Language: Java ⚡ Runtime: 0 ms — Beats 100.00% 📉 Memory: 45.54 MB — Beats 56.30% 🧠 Concept Used: 🔹 Bit Manipulation — A powerful yet tricky technique that leverages binary operations to track occurrences of bits efficiently. 🔹 Instead of using extra space or hash maps, we track bits that appear once and twice using two integer variables: ✅ once → bits that appeared once ✅ twice → bits that appeared twice The trick lies in updating them using XOR (^) and NOT (~) to "cancel out" bits appearing three times. 🧩 Approach Summary: 1️⃣ Initialize two variables once = 0 and twice = 0. 2️⃣ For every number in the array: - Update once and twice based on how many times a bit has appeared. 3️⃣ After processing all numbers, once holds the value of the single element. ✅ Complexity: Time: O(n) Space: O(1) ✨ Takeaway: This problem teaches how bitwise logic can replace traditional data structures, achieving the same result with constant space — a crucial optimization in system-level programming and interviews. #100DaysOfCode #LeetCode #Java #BitManipulation #ProblemSolving #CleanCode #DataStructures #Algorithms #TechLearning #CodingChallenge #SoftwareEngineering #InterviewPreparation
To view or add a comment, sign in
-
-
Day 40 of #100daysOfCode Problem: 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 Difficulty: Medium Language: Java Status: Solved Problem Summary: You're given an array of positive integers nums. In one operation, you can choose an index i (where 0 ≤ i < n - 1) and replace either nums[i] or nums[i+1] with gcd(nums[i], nums[i+1]). You need to find the minimum number of operations to make all elements equal to 1. If it’s not possible, return -1. Key Insight: If there’s at least one 1 in the array → we can convert all other elements to 1 in n - count(1) operations. Otherwise, find the shortest subarray whose GCD = 1. Once found, it takes (j - i) operations to create one 1 and (n - 1) more to make the entire array 1. Algorithm Steps: Count how many elements are 1. If any exist → answer = n - ones. If not → iterate all subarrays, compute GCD until it becomes 1. Keep track of the smallest subarray length that reaches GCD = 1. If none found → return -1. Else return minLength + (n - 1). Time Complexity: O(n² * log(max(nums[i]))) Space Complexity: O(1) Learning Takeaway: Classic GCD reduction logic—search for minimal segment that can “spread” ones across the array. Efficiently reuses math logic in algorithmic reasoning. #Day40 #100DaysOfCode #LeetCode #Math #GCD #Greedy #Java #Algorithms #CodingChallenge #ProblemSolving #DSA
To view or add a comment, sign in
-
-
🚀 Day 416 of #500DaysOfCode Problem: 1513. Number of Substrings With Only 1s Platform: LeetCode – Medium Today’s challenge was a classic binary-string problem that focuses on counting substrings composed only of '1' characters. Sounds simple—but with constraints up to 100,000 characters, brute force is impossible. 🔍 What I Learned The key insight is: Whenever you find a continuous streak of 1s of length k, it contributes: k⋅(k+1)2\frac{k \cdot (k+1)}{2}2k⋅(k+1)substrings made only of 1s. Example: 111 → • "1" (3 times) • "11" (2 times) • "111" (1 time) Total = 6 So instead of checking all substrings, we just: ➡️ Count lengths of 1-streaks ➡️ Use the formula ➡️ Keep sum modulo 1e9+7 🧠 Why This Problem Is Useful Builds intuition for pattern-counting in strings Reinforces how mathematical optimization replaces brute-force loops Helps in understanding frequency-based substring logic 📌 Output Examples Input: "0110111" → Output: 9 Input: "101" → Output: 2 Input: "111111" → Output: 21 💡 Reflection Simple logic + clever math = powerful optimization. This problem reminded me how often the pattern matters more than the individual characters. #500DaysOfCode #Day416 #LeetCode #Java #CodingJourney
To view or add a comment, sign in
-
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
Great 👍