Sorting by Bit Patterns: A Powerful Technique

🔹 Sorting isn’t always about values — sometimes it’s about bit patterns. A powerful yet underrated technique: 👉 Sort numbers based on the number of 1’s (set bits) in their binary representation This pattern appears in real-world problem solving like: • Bitmasking problems • Subset generation • Optimization problems where “active bits” matter 👉 Example: 3 → 11 → 2 set bits 5 → 101 → 2 set bits 8 → 1000 → 1 set bit ✅ Sorted (by set bits, then value): 👉 [8, 3, 5] 💻 Java Implementation: Arrays.sort(arr, (a, b) -> { int countA = Integer.bitCount(a); int countB = Integer.bitCount(b); if (countA != countB) { return countA - countB; } return a - b; }); ⚡ Time Complexity Insight: • Sorting → O(n log n) • bitCount() → O(1) (hardware optimized) 👉 Overall complexity remains O(n log n) 🧠 Optimization Trick (Interview Ready): Avoid recomputing bit counts for large arrays: Map<Integer, Integer> map = new HashMap<>(); for (int num : arr) { map.put(num, Integer.bitCount(num)); } Arrays.sort(arr, (a, b) -> { if (!map.get(a).equals(map.get(b))) { return map.get(a) - map.get(b); } return a - b; }); 🧠 Deeper Insight: This follows the classic pattern: 👉 Decorate → Sort → Undecorate (Schwartzian Transform) • Attach metadata (bit count) • Sort using metadata • Retrieve original values ⚠️ Edge Cases to Think About: • Negative numbers (2’s complement representation) • Duplicate values • Sorting stability 🧠 Alternative Bit Trick: n = n & (n - 1); 👉 Removes the lowest set bit 👉 Useful when bitCount() is unavailable 📌 Key Takeaway: Good engineers don’t just sort data — they define what “sorted” really means based on the problem. 💬 Have you used custom comparators like this in real-world systems or interviews? #bitmanipulation #java #dsa #problemSolving #backenddeveloper #codinginterview #softwareengineering

To view or add a comment, sign in

Explore content categories