Sort Integers by The Number of 1 Bits - Complete Solution Guide
Sort Integers by The Number of 1 Bits is LeetCode problem 1356, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
You are given an integer array arr . Sort the integers in the array in ascending order by the number of 1 's in their binary representation and in case of two or more integers have the same number of 1 's you have to sort them in ascending order. Return the array after sorting it . Example 1: Input: arr = [0,1,2,3,4,5,6,7,8] Output: [0,1,2,4,8,3,5,6,7] Explantion: [0] is the only integer with 0 bits. [1,2,4,8] all have 1 bit. [3,5,6] have 2 bits. [7] has 3 bits. The sorted array by bits is [0,1,
Detailed Explanation
This problem challenges us to reorder an array of integers, but not by their typical numerical value alone. Instead, the primary sorting criterion is the *number of '1' bits* present in their binary representation. Imagine translating each number into its binary form – for instance, 5 is '101' (two '1's), and 6 is '110' (two '1's). Both 5 and 6 would group together because they share the same bit count. After grouping, if multiple numbers have an identical count of '1' bits, then a secondary sorting rule kicks in: they should be sorted by their original numerical value in ascending order.
Solution Approach
The provided solution elegantly leverages Python's built-in `sorted()` function with a custom `key`. The core idea is to transform each number into a sortable 'proxy' that encodes both sorting criteria. By returning a tuple `(bin(x).count('1'), x)` for each integer `x`, we create exactly such a proxy. Python's `sorted()` function (and analogous sorting routines in many languages) performs lexicographical comparison on tuples: it first compares the first elements of the tuples. If they are different, that determines the order. If they are identical, it proceeds to compare the second elements, and so on. This precisely implements our two-tiered sorting requirement: first by the count of '1' bits (from `bin(x).count('1')`), then by the original number itself (`x`) as a tie-breaker, all in ascending order by default.
Step-by-Step Algorithm
- Count the number of set bits (1s) in the binary representation of each integer in the input array.
- Sort the array based on a custom comparison function or key. This function compares the bit counts first; if the bit counts are equal, it compares the integer values.
- Return the sorted array.
Key Insights
- **Leveraging Python's `key` for Multi-Criteria Sorting:** The genius of this approach lies in using the `key` argument of the `sorted()` function to return a tuple. When sorting by multiple criteria, creating a tuple `(primary_criterion_value, secondary_criterion_value)` provides a concise and effective way to dictate sorting precedence. Python's tuple comparison naturally handles the lexicographical ordering, perfectly aligning with the problem's 'sort by bit count, then by value' rule.
- **Efficient Bit Counting with String Methods:** Instead of intricate bit manipulation loops (like Brian Kernighan's algorithm or right-shifting and checking the LSB), this solution opts for a highly readable and often sufficiently performant method: `bin(x).count('1')`. Python's `bin(x)` converts an integer to its binary string representation (e.g., `0b101`), and then the string `count('1')` method efficiently tallies the set bits. This demonstrates that sometimes a clear, high-level approach can be just as effective and much more maintainable than a low-level optimization.
- **Implicit Ascending Order and Stability:** Python's `sorted()` function inherently sorts in ascending order and is stable. This means that when a `key` is applied and tuples are generated, they are compared from left to right, and elements that evaluate to 'equal' by the `key` maintain their original relative order. For this problem, since both the bit count and the number itself need to be sorted ascending, the default behavior of `sorted()` and tuple comparison works perfectly without any need for custom comparison logic or `reverse=True` flags.
Complexity Analysis
Time Complexity: O(n log n)
Space Complexity: O(n)
Topics
This problem involves: Array, Bit Manipulation, Sorting, Counting.
Companies
Asked at: Accenture, J.P. Morgan, Mapbox.