Cardinality Sorting
Updated
Problem statement
The binary cardinality of a number is the total number of 1's it contains in its binary representation. For example, the decimal integer 20 corresponds to the binary number 10100₂. There are 2 1's in the binary representation so its binary cardinality is 2.
Given an array of decimal integers, sort it ascending first by binary cardinality, then by decimal value. Return the resulting array.
Function
cardinalitySort(nums: int[]) → int[]
Complete the function cardinalitySort in the editor.
cardinalitySort has the following parameter(s):
int nums[n]: an array of decimal integers
Returns
int[n]: the integer array nums sorted first by ascending binary cardinality, then by decimal value
Examples
Example 1
nums = [31, 15, 7, 3, 2]return = [2, 3, 7, 15, 31]31₁₀ → 11111₂ so its binary cardinality is 5. 15₁₀ → 1111₂ so its binary cardinality is 4. 7₁₀ → 111₂ so its binary cardinality is 3. 3₁₀ → 11₂ so its binary cardinality is 2. 2₁₀ → 10₂ so its binary cardinality is 1.
Example 2
nums = [1, 2, 3, 4, 5]return = [1, 2, 4, 3, 5]The sorted elements with binary cardinality of 1 are [1, 2, 4]. The array to return is [1, 2, 4, 3, 5].
Example 3
nums = [3]return = [3]Not privided for now.
Example 4
nums = [1, 2, 3, 4, 5]return = [1, 2, 4, 3, 5]Not privided for now.
Constraints
1 ≤ n ≤ 10⁵1 ≤ nums[i] ≤ 10⁶
More Oracle interview questions
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Minimum Meeting RoomsONSITE INTERVIEW · Seen Nov 2026
- Shortest Window with Required CountsONSITE INTERVIEW · Seen Nov 2026
- Maximum Subarray Sum with One DeletionONSITE INTERVIEW · Seen Nov 2026
- Shortest Deletion for Distinct CharactersONSITE INTERVIEW · Seen Nov 2026
- Count Dropped Rate-Limited RequestsONSITE INTERVIEW · Seen Nov 2026
- Remove Parentheses from a Plus-Minus ExpressionPHONE SCREEN · Seen Nov 2026
- Design Authentication ManagerONSITE INTERVIEW · Seen Oct 2026
- Maximum Bouquet ValueONSITE INTERVIEW · Seen Oct 2026
- Trapping Rain WaterPHONE SCREEN · Seen Oct 2026
Similar questions at other companies
- Maximize K-Element AND with an Increment BudgetAmazon · OA
- Count Prefix Subsets with a Given XORGoDaddy · OA
- Minimum Inversions 🍑TikTok · OATikTok interview questions
- Count User Mentions in Chat MessagesRamp · OARamp interview questions
- Catch Fish with Reusable BaitsSusquehanna International Group (SIG) · OASusquehanna International Group (SIG) interview questions
- Competition Winner and Runner-Up (Forward Deployed Engineer)Boston Consulting Group · OABoston Consulting Group interview questions
- Blood Type Inheritance: Possible Parent GenotypesAbridge · OAAbridge interview questions
- Rank Football TeamsCapital One · OACapital One interview questions
- Maximum Apples That Fit in a BoxVirtu Financial · OAVirtu Financial interview questions
- Minimum Testers to Find the Poisoned BottleWalleye Capital · OA