Order Integers by Set-Bit Count Then Value

Quick Overview

Order Integers by Set-Bit Count Then Value. Sort arr by increasing number of1 bits in each value's binary representation.

Order Integers by Set-Bit Count Then Value

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Sort arr by increasing number of 1 bits in each value's binary representation. If bit counts tie, order by increasing numeric value. Return the sorted values, preserving duplicates. ```cpp class Solution { public: vector<int> sortByBits(vector<int>& arr); }; ``` ### Examples **Example 1:** ```text Input: arr = [10,3,8,0,3] Output: [0,8,3,3,10] Explanation: The bit counts are0 for0,1 for8,and2 for3 and10; numeric order resolves the final group. ``` **Example 2:** ```text Input: arr = [15,7,4] Output: [4,7,15] Explanation: Their set-bit counts are1,3,4. ``` ### Constraints - arr contains 1 to 500 integers. - Every value is in `[0,10000]`. ### Contract considerations The complete sorted result is deterministic. ```hint Read the boundary condition Check zero values, duplicate values, and tied bit counts. The numeric tie-break applies only after the bit-count comparison. ``` ### Boundary reminders The complete sorted result is deterministic.

Overview: Order Integers by Set-Bit Count Then Value. Sort arr by increasing number of1 bits in each value's binary representation.

Google logo
Google
Source window: 0–6 months · as of Oct 21, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Sort arr by increasing number of 1 bits in each value's binary representation. If bit counts tie, order by increasing numeric value. Return the sorted values, preserving duplicates.

class Solution {
public:
    vector<int> sortByBits(vector<int>& arr);
};

Examples

Example 1:

Input: arr = [10,3,8,0,3]
Output: [0,8,3,3,10]
Explanation: The bit counts are0 for0,1 for8,and2 for3 and10; numeric order resolves the final group.

Example 2:

Input: arr = [15,7,4]
Output: [4,7,15]
Explanation: Their set-bit counts are1,3,4.

Constraints

  • arr contains 1 to 500 integers.
  • Every value is in [0,10000] .

Contract considerations

The complete sorted result is deterministic.

Boundary reminders

The complete sorted result is deterministic.