Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sorting
Bit Manipulation
Sort Integers By The Number Of 1 Bits

Sort an array of integers by the number of set bits in each number, breaking ties by numeric order.

Acceptance 0%
Problem Statement

Given an array of integers, reorder the elements so that numbers with fewer 1 bits in their binary representation come first. If two numbers have the same number of 1 bits, the smaller numeric value should appear first.

The task is to return the fully sorted array according to this rule.

Input Format

  • An integer array arr.
  • Each value is treated as a non-negative integer for bit counting.

Output Format

  • Return the array sorted by:
    1. Increasing number of set bits (1s) in binary.
    2. Increasing numeric value when bit counts are equal.

Constraints

  • 1 <= arr.length
  • Integers are within a standard 32-bit signed range.
  • Assume bit counts are computed on the integer's binary form.
  • A comparison-based or custom-key sort is expected.
Examples
Sample cases returned by the problem API.

Example 1

Input

[0,1,2,3,4,5,6,7,8]

Output

[0,1,2,4,8,3,5,6,7]

Explanation

Bit counts: 0->0, 1->1, 2->1, 4->1, 8->1, 3->2, 5->2, 6->2, 7->3. Within equal bit counts, values increase.

Example 2

Input

[10,100,1000,10000]

Output

[10,100,10000,1000]

Explanation

Bit counts are 10->2, 100->3, 10000->5, 1000->6, so the order follows increasing set bits.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.