Sort Integers by The Number of 1 Bits
EasyBit Manipulationbit manipulation
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given an array arr of non-negative integers, return a new array with the same values sorted by how many 1 bits each has in its binary representation, fewest first.
When two values have the same number of 1 bits, the smaller value comes first. Duplicates stay in the output.
Examples
Input: arr = [0,1,2,3,4,5,6,7,8]
Output: [0,1,2,4,8,3,5,6,7]
0 has no set bits; 1, 2, 4, 8 have one; 3, 5, 6 have two; 7 has three.
Input: arr = [10,100,1000,10000]
Output: [10,100,10000,1000]
Set-bit counts are 2, 3, 6 and 5, so 10000 (5 bits) comes before 1000 (6 bits).
Constraints
- 1 <= arr.length <= 500
- 0 <= arr[i] <= 10^4
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.