🔢 Day 47/75: Optimizing with Brian Kernighan’s Algorithm! Today’s challenge was counting the number of "1" bits in an integer. While the naive approach is to check all 32 bits one by one, I implemented a much more elegant solution known as Brian Kernighan’s Algorithm. The Logic: The expression n = n & (n - 1) has a fascinating property: it always flips the least significant set bit (the rightmost 1) to 0. By running this in a loop until $n$ becomes 0, the number of iterations equals exactly the number of set bits. If a number has only three "1" bits, the loop runs 3 times, not 32. The Result: ✅ Runtime: 0 ms (Beats 100.00% of Java users) ✅ Efficiency: $O(k)$ time complexity, where $k$ is the number of set bits. Mastering these bitwise shortcuts is what separates a good solution from a great one! 🚀 #75DaysOfCode #LeetCode #Java #BitManipulation #Algorithms #ComputerScience #Optimization #SoftwareEngineering
Optimizing with Brian Kernighan's Algorithm
More Relevant Posts
-
Day 9/ #100DaysOfCode Solved LeetCode 1848: Minimum Distance to the Target Element. Approach: The problem can be solved using a straightforward linear traversal. Iterate through the array and check for indices where the value equals the target. For each such index, compute the absolute difference between the current index and the given start index. Maintain a variable to track the minimum distance encountered during the traversal. Solution Insight: Initialize a variable with a large value (e.g., Integer.MAX_VALUE). Traverse the array once. Whenever the target element is found, update the minimum distance using Math.abs(i - start). Return the minimum value after the loop. Complexity: Time Complexity: O(n) Space Complexity: O(1) Result: 72/72 test cases passed with optimal runtime performance. This problem reinforces the importance of simple iteration and careful tracking of minimum values in array-based problems. #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
📘 DSA Journey — Day 30 Today’s focus: HashMap for frequency counting. Problem solved: • Number of Good Pairs (LeetCode 1512) Concepts used: • HashMap • Frequency counting • Incremental counting technique Key takeaway: The goal is to count pairs (i, j) such that nums[i] == nums[j] and i < j. Instead of checking all pairs (which would take O(n²)), we use a HashMap to track frequencies. As we iterate through the array: • For each number, we check how many times it has already appeared • That count directly contributes to the number of valid pairs • Then we update its frequency in the map This allows counting pairs in a single pass with O(n) time complexity. Continuing to strengthen fundamentals and consistency in problem solving. #DSA #Java #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
Day 74 of #100DaysOfLeetCode 💻✅ Solved #162. Find Peak Element problem in Java. Approach: • Used Binary Search technique to efficiently find the peak element • Set two pointers, left at start and right at end of the array • Calculated mid index using safe mid formula • Compared nums[mid] with nums[mid + 1] to determine direction • If mid element is smaller, moved search space to right half • Otherwise, moved search space to left half including mid • Continued until left and right pointers converged • Final position (left == right) represents the peak index Performance: ✓ Runtime: 0 ms (Beats 100.00% submissions) 🚀 ✓ Memory: 44.32 MB (Beats 25.49% submissions) Key Learning: ✓ Strengthened understanding of Binary Search on unsorted arrays ✓ Learned how to apply divide-and-conquer beyond traditional searching ✓ Improved intuition for peak finding using neighbor comparison ✓ Practiced optimizing search space instead of linear scanning Learning one problem every single day 🚀 #Java #LeetCode #DSA #BinarySearch #Arrays #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 571 of #750DaysOfCode 🚀 🔍 Problem Solved: Sum of Distances Today’s problem looked like a classic brute-force trap 👀 At first glance, comparing every pair gives an O(n²) solution — but with constraints up to 10⁵, that’s not going to work. 💡 Key Insight: Instead of comparing all pairs, we can: 👉 Group indices of the same value 👉 Use prefix sums to efficiently calculate distances 🧠 Approach: Group indices by value (using HashMap) For each group: Build prefix sum of indices For each index: Left contribution → i * count - sum Right contribution → sum - i * count Combine both to get final result 📈 Complexity: Time: O(n) Space: O(n) ✨ Takeaway: When you see distance-based problems: 👉 Think in terms of contributions instead of pair comparisons 👉 Prefix sums can turn expensive computations into linear time Another strong pattern added to the toolkit 💪 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #PrefixSum #Algorithms #LearningEveryday
To view or add a comment, sign in
-
-
Continuing my DSA journey, * Problem: Number of Atoms (726) * Approach: -I solved this using a stack-based parsing approach. -I used a stack of maps to keep track of atom counts at different levels. While iterating through the string: -On '(' → push a new map onto the stack -On ')' → pop the top map, multiply counts, and merge back -For elements → parse the name and count, then update the current map * Key Insight: -The tricky part was handling nested parentheses and applying multipliers correctly. -Using a stack helps manage different scopes efficiently. * What I Learned: This problem improved my understanding of string parsing with stacks. #LeetCode #DSA #Java #Stack #Strings #ProblemSolving
To view or add a comment, sign in
-
-
🧠 Day 36/75: Recursion within Recursion! Today’s challenge was "Subtree of Another Tree," a problem that perfectly illustrates how we can reuse fundamental patterns to solve more complex structures. The Strategy: To solve this, I combined two recursive ideas: Traverse the Main Tree: A standard DFS to visit every node in the primary tree. Structural Comparison: At every node, I used a helper function (isSameTree) to check if the current subtree perfectly matches the target structure. Performance: ✅ Runtime: 3 ms (Beats 67.99% of Java users) ✅ Complexity: $O(M \times N)$ in the worst case, but highly efficient for most tree structures. It’s incredibly satisfying to see yesterday's "Same Tree" logic become just one small part of today's larger solution. Build, repeat, and scale! 🚀 #LeetCode #75DaysOfCode #Java #BinaryTree #Recursion #DSA #SoftwareEngineering #ProblemSolving
To view or add a comment, sign in
-
-
Day 71/100 Completed ✅ 🚀 Solved LeetCode – Reshape the Matrix (Java) ⚡ Implemented an efficient matrix transformation approach by mapping elements from the original matrix to the reshaped matrix using a single traversal. Instead of creating intermediate structures, used index manipulation (count / c, count % c) to place elements correctly while maintaining row-wise order. 🧠 Key Learnings: • Understanding how to map 2D indices into a linear traversal • Efficiently converting between different matrix dimensions • Handling edge cases where reshape is not possible • Writing clean and optimized nested loop logic 💯 This problem strengthened my understanding of matrix traversal and index mapping techniques, which are very useful in array and grid-based problems. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #arrays #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
💡 Day 61 of LeetCode Problem Solved! 🔧 🌟 482. Find Maximum Consecutive Ones 🌟 🔗 Solution Code: https://lnkd.in/gf5DPq4E 🧠 Approach: • Traverse the binary array once using one pointer. • Keep counting consecutive 1s and update the maximum value at each step. • When a 0 appears, reset the count to 0. ⚡ Key Learning: • This is a simple sliding window idea. No need for nested loops or extra memory. Tracking current count and maximum value is a useful pattern for many array problems. ⏱️ Complexity: • Time: O(N) • Space: O(1) #LeetCode #Java #DSA #ProblemSolving #Consistency #CodingJourney #Algorithms #Arrays
To view or add a comment, sign in
-
-
Day 51 of Daily DSA 🚀 Solved LeetCode 83: Remove Duplicates from Sorted List ✅ Problem: Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Approach: Used a single pointer traversal since the list is already sorted, making duplicate detection straightforward. Steps: Start from head node Compare current node with next node If values are same → skip next node Else move current pointer forward Continue until end of list Return updated head ⏱ Complexity: • Time: O(n) • Space: O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 45.48 MB Sorted input often simplifies the logic — duplicates become adjacent and easy to remove. #DSA #LeetCode #Java #LinkedList #CodingJourney #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
Day 72/100 Completed ✅ 🚀 Solved LeetCode – Matrix Diagonal Sum (Java) ⚡ Implemented an efficient approach to calculate the sum of both primary and secondary diagonals of a square matrix in a single traversal. Avoided double-counting the center element by handling the odd-sized matrix case separately. 🧠 Key Learnings: • Efficient diagonal traversal in a matrix • Handling overlapping elements (center in odd n) • Writing optimal O(n) solutions instead of nested loops • Clean and concise index-based logic 💯 This problem improved my understanding of matrix patterns and how to optimize traversal by reducing unnecessary iterations. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #arrays #problemSolving #100DaysOfCode 🚀
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