Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Sort Integers by The Number of 1 Bits

XPChallenge Points: 10
levelLevel: Easy

Given an array of integers, your task is to rearrange the elements based on how many 1s appear in their binary form.
The sorting must follow these rules:

  1. Numbers with fewer 1-bits should appear earlier.

  2. If two values contain the same number of 1-bits, sort them by their natural ascending order.

  3. Return the final sorted array.

Example 1:

Input: arr = [5, 3, 9, 6]

Output: [3, 5, 6, 9]

Explanation:

Binary forms: 5 → 101 (2 ones) 3 → 011 (2 ones) 9 → 1001 (2 ones) 6 → 110 (2 ones) All have equal bit-count → sort normally.

Example 2:

Input: arr = [7, 8, 1, 2]

Output: [1, 2, 8, 7]

Explanation:

Binary: 7 → 111 (3 ones) 8 → 1000 (1 one) 1 → 1 (1 one) 2 → 10 (1 one) 1-bit group → [1, 2, 8] (sorted) 3-bit group → [7]

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result