Problem 1356

Abstract / Summary

Sort integers based on how many 1 bits they have in their binary form

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1356.py

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        return [ b % 100_000 for b in sorted([ 100_000 * a.bit_count() + a for a in arr ])]
3 lines | 166 bytes | submitted October 30, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 82% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Counting
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single method sortByBits. The method receives a list of integers and returns a new list where the integers are ordered first by the number of set bits in their binary representation and then by their numeric value. The implementation achieves this ordering by constructing a composite key for each element, sorting based on that key, and finally extracting the original values.

Key Steps

The algorithm can be broken down into three conceptual stages: key construction, sorting, and result extraction.

Key Construction

[100_000 * a.bit_count() + a for a in arr]

For each integer a in the input list, the expression computes the number of set bits using a.bit_count(). This count is multiplied by a large constant (100_000) and then the original value a is added. The constant is chosen to be larger than any possible input value, ensuring that the bit-count dominates the ordering while preserving the original value as a secondary tie-breaker.

Sorting

sorted([100_000 * a.bit_count() + a for a in arr])

The list of composite keys is passed to Python’s built-in sorted function. Because the keys are integers, the sort operates on a single numeric value per element, which is highly efficient. The ordering produced by sorted respects the intended primary and secondary criteria encoded in the composite key.

Result Extraction

[ b % 100_000 for b in sorted([...]) ]

After sorting, each composite key b is reduced modulo 100_000. This operation discards the high-order part that encoded the bit count, leaving only the original integer value. The resulting list contains the input numbers arranged according to the required ordering.

Edge Cases Handled

The design implicitly handles several edge conditions without additional code.

When the input list is empty, the list comprehension produces an empty list, sorted returns an empty list, and the final list comprehension also yields an empty list. Thus the method returns an empty list as expected.

If the input contains duplicate values, each duplicate generates an identical composite key. The stable nature of Python’s sort ensures that duplicates retain their relative order, which aligns with the requirement that equal values remain adjacent after sorting.

The use of a.bit_count() works for any non-negative integer, including zero. For a = 0, the bit count is zero, and the composite key becomes simply 0. This correctly places zero at the beginning of the sorted result when no other numbers have a zero bit count.

The constant 100_000 is larger than the maximum possible element value in the problem’s typical constraints (values up to 10^5). Consequently, the multiplication never overflows the intended ordering scheme, and the modulo operation reliably recovers the original value.

Performance Optimizations

The implementation leverages a single pass to create the composite keys, avoiding the need for a separate data structure to store both the bit count and the original value. By encoding both criteria into a single integer, the sort operates on a flat list of primitives, which is faster than sorting a list of tuples or custom objects.

Using the built-in sorted function benefits from CPython’s highly optimized Timsort algorithm, which performs well on partially ordered data and minimizes the number of comparisons. Because the keys are integers, each comparison is a simple numeric operation.

The final modulo operation is a constant-time arithmetic step that efficiently strips away the high-order component of each key. This avoids any additional look-ups or dictionary accesses that might be required if the original values were stored separately.

Overall, the code achieves the desired ordering with minimal overhead, relying on Python’s native integer arithmetic and sorting facilities to deliver a concise and performant solution.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of mixed-up toys that need to be put away. Each toy has a secret number etched on the bottom. To tidy them up, a special trick is used to look at these numbers.

First, look at each number and count how many little ones are hiding inside its binary code. Binary is like a hidden language made only of ones and zeros. Once you know how many ones are in each number, you write a new, much larger number on a sticky note and put it on the toy. This new number is made by taking the count of ones, multiplying it by one hundred thousand, and then adding the original secret number.

Now that every toy has a sticky note, you line them all up in order from the smallest sticky note number to the biggest one. Because all the counts of ones were multiplied by such a huge amount, all the toys with the same number of ones naturally end up sitting right next to each other in a neat little group.

Finally, you peel off the part of the sticky note you added, which leaves you with the original secret numbers perfectly organized. The toys with fewer ones appear first, and if two toys have the same amount, the one with the smaller secret number comes first. Everything is now arranged in a perfect line just the way you wanted.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.74 | σ = 1.71

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C Go Rust TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
martianoff Scala
varunu28 Java
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
martianoff Scala
varunu28 Java
withaarzoo C++
31 links | 18 authors | 11 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

1 medium 2 hard
4 solutions   October 30, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality