Sort by Most Frequent DigitMedium

Sort by Most Frequent Digit

MediumPractice library · +20 XPsortingcounting sort

Given a list of N integers, sort them in ascending order. If two numbers have the same most frequent digit in their decimal representation, sort them in ascending order. The most frequent digit is defined as the digit that appears most often. If there's a tie for the most frequent digit, consider the smallest of the tied digits.

Input

The first line contains an integer N. The second line contains N space-separated integers.

Output

Print the N sorted integers on a single line, separated by spaces.

Constraints

1 <= N <= 200000, 0 <= arr[i] <= 10^9

Time limit 1 s (native code; slower languages get more)Memory 256 MB14 hidden tests

Example 1

Input
5
123 321 112 211 122
Output
112 123 211 321 122

123 (1), 321 (1), 112 (1), 211 (1), 122 (2). Sorted by most frequent digit: 112, 123, 211, 321, 122. Then by value: 112, 123, 211, 321, 122.

Example 2

Input
4
100 200 110 220
Output
100 200 110 220

100 (0), 200 (0), 110 (1), 220 (2). Sorted by most frequent digit: 100, 200, 110, 220. Then by value: 100, 200, 110, 220.

Hints