classSolution {// It is guaranteed an answer exists.publicint[] rearrangeBarcodes(int[] barcodes) {// map of barcode -> frequencyHashMap<Integer,Integer> map =newHashMap<>();int max =0;// O(n)for (int barcode : barcodes) {map.put(barcode,map.getOrDefault(barcode,0) +1); max =Math.max(map.get(barcode), max); }// List of frequency -> barcodesList<Integer>[] freq =newArrayList[max +1];// frequency is index// O(n)for (int barcode :map.keySet()) {if (freq[map.get(barcode)] ==null) freq[map.get(barcode)] =newArrayList<>(); freq[map.get(barcode)].add(barcode); }int[] ans =newint[barcodes.length];int index =0;// O(2n) at worst case, because number of elements// in total frquency ArrayLists will be 'n'for (int i = max; i >=1; i--) {if (freq[i] !=null) {for (int barcode : freq[i]) {for (int count = i; count >0; count--) {if (index >=ans.length) index =1; ans[index] = barcode; index +=2; } } } }return ans; }}