package com.xxx.amp.magenta.livecodebench.solution;

import java.util.*;

public class CanSortSolution {
    public boolean canSortArray(int[] nums) {
        // Create a map to group numbers by their number of set bits
        Map<Integer, List<Integer>> bitCountMap = new HashMap<>();

        for (int num : nums) {
            int setBits = Integer.bitCount(num);
            bitCountMap.putIfAbsent(setBits, new ArrayList<>());
            bitCountMap.get(setBits)
                    .add(num);
        }

        // Create a sorted version of the original array
        int[] sortedNums = nums.clone();
        Arrays.sort(sortedNums);

        // Check if we can sort the array by comparing the sorted array
        // with the grouped elements based on their set bits
        List<Integer> sortedList = new ArrayList<>();
        for (int key : bitCountMap.keySet()) {
            List<Integer> group = bitCountMap.get(key);
            Collections.sort(group);
            sortedList.addAll(group);
        }

        // Compare the sorted list with the sorted version of the original array
        for (int i = 0; i < nums.length; i++) {
            if (sortedList.get(i) != sortedNums[i]) {
                return false;
            }
        }

        return true;
    }
}
