Triple sorting: frequency, length, lexicographically

Python Hard sorting

Task «Triple sorting: frequency, length, lexicographically»

Given a list of strings. Sort the strings according to three criteria: first by decreasing frequency of occurrence of the string in the original list, then by increasing length of the string, and finally lexicographically (in increasing order, standard string comparison). If two strings have the same frequency and length, they are compared lexicographically. Implement the sorting without using the built-in sort function with a custom key (prohibited), but only using your own sorting function (e.g., quicksort, merge sort, or another). Input data: first an integer N (1 ≤ N ≤ 10^5) — the number of strings, then N strings. Output the strings in sorted order, each on a new line. Time limit: 2 seconds, memory limit: 256 MB.

Input Format

The first line contains an integer N (1 ≤ N ≤ 10^5). Then follow N lines, each may contain any printable characters (except spaces), the length of each line is from 1 to 20 characters.

Output Format

Output N lines in the required order, each on a separate line.

Examples

Example 1

INPUT
1 10
OUTPUT
17

Example 2

INPUT
5 3 1 4 1 5
OUTPUT
3 1 4 1 5
main.py