Sort Integers by Binary 1s and Decimal Value

One-Line Sorting with Custom Lambda Key (Sort Integers by The Number of 1 Bits) 💯 || O(N log N) || Just tackled a fun bit-manipulation and sorting problem on LeetCode (Problem 1356), and I wanted to share a super clean, Pythonic way to solve it! 🐍 🎯 The Problem: Sort an array of integers based on the number of 1s in their binary representation. If two numbers have the same number of 1s, sort them by their decimal value. 💡 The Approach: Instead of writing a complex custom comparator, Python’s built-in sorting handles multi-level conditions beautifully. By passing a list [primary_condition, secondary_condition] to the key argument, Python sorts by the first element and automatically falls back to the second if there's a tie. Here is the one-liner: Python class Solution: def sortByBits(self, arr: List[int]) -> List[int]: return sorted(arr, key=lambda x: [bin(x).count('1'), x]) 📊 Complexity: Time: O(N log N) — Python's Timsort algorithm does the heavy lifting, and counting bits for 32-bit integers takes O(1) time. Space: O(N) — Using sorted() creates a new list. Pro-Tip: If you want to optimize for space, you can swap sorted(arr, ...) for arr.sort(...) to sort the array in-place! What is your favorite Python built-in function or one-liner tip? Let me know in the comments! 👇 #Python #LeetCode #Algorithms #CodingInterviews #SoftwareEngineering #DataStructures

To view or add a comment, sign in

Explore content categories