#3769
Sort Integers by Binary Reflection
EasyArraySortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
We can create a list of tuples containing the binary reflection and the original number, then sort this list. This reduces the number of operations significantly.
⚙️
Algorithm
3 steps- 1Step 1: Create a list of tuples where each tuple contains the binary reflection and the original number.
- 2Step 2: Sort this list based on the binary reflection first, and the original number second.
- 3Step 3: Extract the sorted original numbers from the sorted list.
solution.py2 lines
1def sortByBinaryReflection(nums):
2 return [num for _, num in sorted((int(bin(num)[:1:-1], 2), num) for num in nums)]ℹ
Complexity note: The sorting step dominates the complexity, making it O(n log n) overall, while storing tuples requires O(n) space.
- 1Binary reflection can be computed efficiently using string manipulation.
- 2Sorting based on multiple criteria is straightforward with tuples.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.