🚀 Today’s LeetCode Problem — Sort Integers by Number of 1 Bits Let’s solve today’s LC in story mode 🎭 Imagine numbers are contestants in a Binary Costume Contest. Today’s contestants: 👉 [5, 3, 7] But this contest has a twist 👇 👨⚖️ The judge doesn’t care about the number itself first. He cares about… 🎈 How many 1s are in their binary costume 🎭 What Are They Wearing? 🔹 5 → 101 → 🎈🎈 (2 ones) 🔹 3 → 011 → 🎈🎈 (2 ones) 🔹 7 → 111 → 🎈🎈🎈 (3 ones) 🏆 Judge’s Rules 1️⃣ Fewer 1s → Higher priority 2️⃣ Same number of 1s → Smaller number wins 👉 Step 1: 3 & 5 → 2 ones 7 → 3 ones So 7 goes last. 👉 Step 2: Tie between 3 and 5 Smaller number first → 3 before 5 ✅ Final Answer: [3, 5, 7] 💡 How I Solved It I implemented this using: 🔹 Brian Kernighan’s Algorithm for efficient bit counting 🔹 TreeMap to maintain sorted order by bit count + value 🔹 Also compared with built-in bitCount() + custom comparator sorting This ensures: ✔ Efficient bit counting ✔ Clean tie-breaking ✔ Optimal sorting logic If you’re interested, I’ve pushed the complete solution (Kernighan + TreeMap + built-in approach) : https://lnkd.in/gV9HZ9w4 👨💻 Would love feedback from fellow developers 🙌 #LeetCode #DSA #Java #ProblemSolving #CodingJourney #100DaysOfCode #Tech #SoftwareEngineering
Sort Integers by Binary 1 Bits
More Relevant Posts
-
🚀 LeetCode Progress Update | Strengthening Core Logic & DSA Today, I tackled the classic "String to Integer (atoi)" problem on LeetCode — and what initially seemed straightforward turned out to be a great exercise in handling edge cases and writing robust logic. While implementing the solution, I realized how important it is to think beyond the obvious. The problem involves handling multiple real-world scenarios such as: Leading whitespaces Optional '+' or '-' signs Non-numeric characters Overflow and underflow conditions One of the key learnings from this problem was understanding how 32-bit integer limits work. In Java, an int can store values only within the range: -->( -2³¹ to 2³¹ - 1) i.e., -2,147,483,648 to 2,147,483,647 So, while parsing a number from a string, if the value exceeds this range: It must be clamped to Integer.MAX_VALUE (2147483647) Or Integer.MIN_VALUE (-2147483648) To handle this effectively, I used a larger data type during computation and carefully controlled overflow conditions — which gave me deeper insight into how real-world systems prevent crashes and unexpected behavior. 💡 This problem reinforced: The importance of edge-case handling Writing defensive and scalable code How exception handling (like try-catch) plays a role when dealing with numeric limits Solving this medium-level problem (with a relatively low acceptance rate) definitely boosted my confidence and strengthened my problem-solving approach. Looking forward to solving more such challenges and continuously improving my DSA and logical thinking skills! 💪 Big thanks to LeetCode for providing such a powerful platform for learning and growth. #LeetCode #DSA #Java #ProblemSolving #CodingJourney #SoftwareEngineering #Developers #TechGrowth #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 29/60 — LeetCode Discipline Problem Solved: Longest Common Prefix Difficulty: Easy Today’s problem focused on identifying the longest common starting pattern across multiple strings — a classic exercise in string comparison and iteration. The approach involved checking characters position by position across all strings until a mismatch is found. This reinforces how simple iterative logic can elegantly solve problems involving multiple inputs. It’s a reminder that sometimes, clarity in approach matters more than complexity in code. 💡 Focus Areas: • Strengthened string traversal techniques • Practiced comparing multiple inputs efficiently • Improved understanding of edge cases (empty strings, mismatch handling) • Reinforced early stopping conditions for optimization • Focused on clean and readable logic ⚡ Performance Highlight: Achieved efficient runtime with minimal overhead. Finding common ground across multiple inputs is not just a coding skill — it’s a pattern recognition mindset. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #Strings #Algorithms #ProblemSolving #CodingJourney #SoftwareEngineering #Java #Developers #Consistency #TechGrowth #LearnToCode
To view or add a comment, sign in
-
-
Day 36 :- Binary Search & Range Finding: Find First and Last Position of Element ✅ Today’s DSA session was a great exercise in extending the classic Binary Search to handle multiple occurrences of a target value. I tackled LeetCode 34. Find First and Last Position of Element in Sorted Array, focusing on how to efficiently pinpoint a range within a sorted dataset. The Technical Breakdown: Hybrid Search Strategy: I started with a standard Binary Search to find any instance of the target. This immediately gives us an O(log n) starting point. Linear Expansion: Once the target was found, I used two pointers to expand outward from the meeting point. This identifies the exact boundaries where the target values start and end. Edge Case Handling: The logic naturally handles cases where the target isn't present by returning [-1, -1], and it manages single-element arrays or cases where the target spans the entire array. The Trade-off: While this approach is very intuitive, it can reach O(n) in the worst case (e.g., an array of all identical numbers). It’s a great stepping stone before diving into the pure O(log n) approach of finding the "leftmost" and "rightmost" indices independently! It's a solid reminder that Binary Search isn't just for finding a single value—it's the foundation for navigating any sorted range! 🚀 A huge thanks to my mentor, Anchal Sharma and Ikshit .. for the incredible support and for helping me stay consistent on this journey. Having that accountability makes all the difference! #DSA #Java #100DaysOfCode #BinarySearch #TwoPointers #ProblemSolving #Mentorship #LeetCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 61 - LeetCode Journey Solved LeetCode 81: Search in Rotated Sorted Array II (Medium) today — a problem that combines binary search + edge case handling + duplicates. This isn’t just a normal binary search. Here, the array is rotated and may contain duplicates, which makes the decision logic more subtle. 💡 Core Idea: At every step, determine which half is sorted. Then decide whether the target lies in that sorted half. If duplicates block the decision, carefully shrink the search space. ⚡ Key Learning Points: • Applying binary search on a rotated array • Handling duplicate values that break clear ordering • Smart boundary adjustments (low++, high--) • Maintaining efficiency close to O(log n) in most cases The real challenge was not writing the code — It was thinking clearly about all possible scenarios. Problems like this strengthen pattern recognition and deepen understanding of search-based algorithms 💯 ✅ Stronger grip on modified binary search ✅ Better handling of tricky edge cases ✅ Improved logical decision-making Each variation of binary search builds sharper intuition. Still learning. Still improving. Still coding 🚀 #LeetCode #DSA #Java #BinarySearch #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
🚀 Day 132 of #1000DaysOfCode LeetCode Daily Challenge — Day 56 56 days. Zero breaks. Steady execution. Today’s problem revolved around custom sorting logic using bit manipulation — ordering integers based on the number of set bits with a well-structured comparator. Key takeaways: • Strengthened understanding of custom comparator design • Applied bitCount effectively within sorting logic • Reinforced hybrid thinking: bit manipulation + sorting • Improved clarity in writing clean and optimized Java solutions ✔️ Accepted solution 🔁 56-Day Coding Streak At this stage, pattern recognition is becoming faster. Less hesitation. More structure. Cleaner implementation. Onward to 60 days. 🚀 #LeetCode #Consistency #Algorithms #DataStructures #Java #BitManipulation #Sorting #ProblemSolving #SoftwareEngineering #CodingJourney
To view or add a comment, sign in
-
-
Day 59 - LeetCode Journey Solved LeetCode 41: First Missing Positive (Hard) today — a problem that truly tests deep understanding of arrays, indexing, and optimization. This isn’t just about coding, it’s about thinking in-place, minimizing space, and using constraints smartly. 💡 Core Idea: Instead of using extra space, we treat the array itself as a hash map and place each element at its correct index (value → index mapping). This transforms the problem into finding the first index where the expected value is missing. ⚡ Approach Highlights: • Cyclic placement of elements to their correct positions • Ignoring invalid values (≤ 0 or > n) • Swapping until every valid number is at its right index • Final scan to find the first missing positive 🚀 Why this is powerful: • Achieves O(n) time complexity • Uses O(1) extra space • Demonstrates in-place hashing technique • Strengthens understanding of index manipulation patterns These are the kinds of problems that build real interview-level thinking — not just solving, but optimizing 💯 Every hard problem pushes boundaries a little further. Slow progress is still progress. ✅ Improved understanding of in-place algorithms ✅ Better optimization mindset ✅ Stronger grip on edge cases Still learning. Still improving. Still coding 🚀 #LeetCode #DSA #Java #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #Algorithms #DataStructures #Arrays #Optimization #InterviewPreparation #KeepCoding #GrowthMindset
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 3 Problem: 1545. Find Kth Bit in Nth Binary String Topic: String, Recursion, Divide and Conquer 🧠 Approach (Simple Thinking): 🔹 Every string Sn is made of 3 parts: The previous string S(n-1) on the left A single "1" sitting right in the middle The flipped and reversed version of S(n-1) on the right 🔹 The string doubles in size every level by S20 you're looking at 1M+ characters. Building it fully? Not a chance. So instead, we recursively figure out which part position k falls into 🔹 If k is in the left half → it behaves exactly like S(n-1). Just recurse with the same k and go one level down 🔹 If k is exactly the middle → no need to recurse at all. The middle is always '1', guaranteed by construction 🔹 If k is in the right half → the right half is a mirror of the left half but with all bits flipped. So we calculate the mirrored position, recurse into the left half to get that bit, and then flip the answer 🔹 Base case → when n = 1, the string is just "0". Return it and start unwinding ⏱️ Time Complexity: Recurse at most n levels deep → O(n) n = the level of the binary string 📦 Space Complexity: Recursive call stack depth is n → O(n) No extra arrays or data structures created 📝 Put together a full walkthrough covering the approach, dry run, and code explanation. 👉 check it out here: https://lnkd.in/gGrReU9W Got a different way to tackle this? Always curious to see alternate approaches share it in the comments below! 🙌 Until the next one, happy coding! 🚀 #LeetCode #Java #SoftwareEngineer #ProblemSolving #BackendDeveloper
To view or add a comment, sign in
-
-
🚀 Day 30/60 — LeetCode Discipline Problem Solved: 3Sum Closest Difficulty: Medium Today’s problem pushed beyond exact answers and focused on finding the closest possible sum to a given target — a subtle yet powerful variation of the classic 3Sum problem. By sorting the array and using a two-pointer approach, the solution efficiently explores combinations while continuously updating the closest result. This problem highlights how small modifications in logic can significantly change the nature of a problem — from exact matching to optimal approximation. 💡 Focus Areas: • Strengthened two-pointer technique • Practiced working with sorted arrays • Improved handling of optimization conditions • Learned to track and update closest values dynamically • Reinforced problem-solving under constraints ⚡ Performance Highlight: Achieved efficient runtime with optimized traversal. Not every problem asks for perfection — sometimes, the goal is to get as close as possible. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #TwoPointers #Algorithms #ProblemSolving #CodingJourney #SoftwareEngineering #Java #Developers #Consistency #TechGrowth #LearnToCode
To view or add a comment, sign in
-
-
🚀 Day 134 of #1000DaysOfCode LeetCode Daily Challenge — Day 58 58 consecutive days of structured problem solving. Discipline is now default. Today’s challenge required careful state tracking, ordered set usage, and boundary management — combining logic precision with efficient data structure handling. Key takeaways: • Strengthened understanding of ordered data structures (TreeSet / lower_bound logic) • Improved range-based iteration with controlled updates • Practiced optimizing transitions between states • Reinforced writing scalable solutions under higher constraints ✔️ Accepted solution 🔁 58-Day Coding Streak Not every problem is about speed. Some are about staying composed when logic becomes layered. Two more days to 60. 🚀 #LeetCode #Consistency #Algorithms #DataStructures #Java #ProblemSolving #SoftwareEngineering #CodingJourney #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 78 / 100 – LeetCode Daily Challenge 🧠 Problem: Triconic Subarray Maximum Sum 📅 Date: March 7, 2026 🏆 Runtime: 3 ms | Beats 99.94% 📦 Memory: 95.28 MB | Beats 46.16% 📝 Problem Insight Today’s challenge was to find the maximum sum of a triconic subarray – a sequence that first decreases, then increases, and finally decreases again. It’s like a "mountain" with two peaks and one valley in between, but in a specific order: down → up → down. This is a more complex variant of the classic mountain or bitonic subarray problems. It requires careful scanning of the array to detect valid triconic patterns and compute their sums efficiently. 💡 My Approach I used a two-pointer expansion method: Iterate through the array and treat each index as a potential peak or valley. Expand left and right while the pattern matches the triconic property. Keep track of the maximum sum encountered. Although the code snippet is incomplete here, the full solution involves: Precomputing left and right decreasing/increasing trends. Validating the three-phase pattern for each possible center. Avoiding redundant computations to keep the time complexity close to O(n). 📊 Results ✅ 861 / 861 test cases passed ⚡ Runtime: 3 ms (beats 99.94% of Java submissions) 📈 Memory: 95.28 MB (beats 46.16%) 🧠 Key Takeaway Pattern recognition problems like this one are great for sharpening your array traversal logic and understanding how to break down complex patterns into manageable checks. The challenge is not just in finding the sum, but in ensuring the pattern holds throughout. 🔗 Let’s Connect! I’m documenting my #100DaysOfCode journey every day – follow along for more problem-solving insights, optimizations, and LeetCode grind! 💻⚡ #LeetCode #Java #CodingChallenge #100DaysOfCode #Day78 #TriconicArray #ProblemSolving #TechJourney #SoftwareEngineering #Algorithms #DataStructures #CodeNewbie #DevCommunity #Programming
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