MICROSOFT Coding Question – Solved

6 Live
The binary cardinality of a number is the count of 1's in its binary representation. For example, the decimal number 10 corresponds to the binary number 1010, which has a binary cardinality of 2 because it contains two 1's. Given an array of decimal integers, sort it by: 1. Increasing binary cardinality (primary criterion) 2. Increasing decimal value (secondary criterion, when cardinalities are equal) Return the sorted array. Example n=4 nums = [1, 2, 3, 4] 110 → 12, so 1's binary cardinality is 1. 210 → 102, so 2's binary cardinality is 1. 310 → 112, so 3's binary cardinality is 2. 410 → 1002, so 4's binary cardinality is 1. The sorted elements with binary cardinality of 1 are [1, 2, 4]. The array to return is [1, 2, 4, 3]. Function Description: Complete the function cardinalitySort in the editor with the following parameter(s): int nums[n]: an array of decimal integers Returns int[n]: the integer array nums sorted ascending, by binary cardinality, then by decimal value for ties. Constraints: 1 ≤ n ≤ 10^5, 1 ≤ nums[i] ≤ 10^6 STDIN Input Format for Custom Testing: Sample Case 0 Sample Input 0: nums size n = 5 nums = [31, 15, 7, 3, 2] Sample Output 0: [2, 3, 7, 15, 31] Explanation 0: 3110 → 11111 so its binary cardinality is 5. 1510 → 1111 so its binary cardinality is 4. 710 → 111 so its binary cardinality is 3. 310 → 11 so its binary cardinality is 2. 210 → 10 so its binary cardinality is 1. Sort the array by ascending binary cardinality and then by ascending decimal value: nums sorted = [2, 3, 7, 15, 31]. Sample Case 1: Sample Input 1: nums size n = 1 nums = [3] Sample Output 1: [3] Explanation 1: The binary cardinality of 310 → 11 is 2. The function returns nums sorted = [3].

Asked in: MICROSOFT

Image of the Question

Question Image Question Image Question Image

All Testcases Passed ✔



Passcode Image

Solution


def cardinalitySort(nums):
    array = []
    for num in nums:
        count = 0
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
To solve this problem, you need to sort an array of decimal integers based primarily on their binary cardinality (the number of 1’s in their binary representation) and secondarily on their decimal values if two numbers share the same binary cardinality. This requires careful consideration of both sorting criteria and an efficient way to compute binary cardinalities due to the large input size constraints.

Let’s break down the approach step-by-step:

1. **Understanding Binary Cardinality**
Binary cardinality of a number is the count of 1 bits in its binary representation. For example, 10 in binary is 1010, which has two 1’s, so its cardinality is 2. The first step is to find a method to calculate this binary cardinality efficiently for each element in the array.

2. **Efficient Computation of Binary Cardinality**
Since the array size can be up to 10^5 and numbers can be as large as 10^6, computing the cardinality for each number must be efficient. Counting bits one-by-one using naive methods might be slow.
- Think about using bit manipulation techniques like Brian Kernighan’s algorithm which repeatedly clears the least significant set bit until the number becomes zero. This method counts the number of 1’s in O(k) where k is the number of set bits, which is often efficient.
- Alternatively, built-in functions or intrinsic operations in some languages can compute this very fast.
- Consider also that the binary cardinality can be precomputed and cached if the range allows, but since numbers go up to 10^6, computing on the fly with an efficient method is preferable.

3. **Sorting Criteria**
Once you can quickly compute the binary cardinality of each number, you must sort the array based on two criteria:
- Primary: Ascending order of binary cardinality.
- Secondary: If two numbers have the same binary cardinality, sort them by their decimal value in ascending order.

4. **Implementing the Sorting**
Think about how sorting algorithms handle custom comparators or key functions. The approach should be to create a list of pairs or tuples where each element is paired with its binary cardinality. For example, convert each number `x` into a tuple `(cardinality(x), x)`.
Then, sort this list of tuples using the default sorting order which naturally sorts first by the first element of the tuple, and then by the second element when there is a tie. This ensures the correct sorting order without needing complex logic.

5. **Algorithmic Complexity**
- Computing binary cardinalities for all elements will take O(n * bit_count_time). With efficient bit counting, this is manageable.
- Sorting the array of size n with keys is O(n log n), which is acceptable for n up to 10^5.
- Overall complexity is dominated by sorting.

6. **Edge Cases**
- If the array contains only one element, it is already sorted.
- All elements having the same binary cardinality means the sort order reduces to sorting by decimal values only.
- Large values with few set bits (like powers of two) must be handled correctly.
- Duplicate elements: sorting should keep all duplicates in the correct order according to their decimal values.

7. **Final Output**
Return the array sorted by the criteria above. The returned array should be a simple list of integers sorted as per the problem statement.

**Summary of the approach:**
- Compute the binary cardinality of each number efficiently.
- Pair each number with its binary cardinality.
- Sort the array based on these pairs with the binary cardinality as the primary key and decimal value as the secondary key.
- Return the sorted array.

This method is direct, efficient, and respects the constraints, providing a clean and understandable solution.
```


Related Questions