Start free

Advanced · Sorting algorithms · 172 of 264

Sort by frequency

Sort the letters of a word by how often they appear, most frequent first; equally frequent letters in alphabetical order. Keep repeats together.

Input: a word in small letters. Output: the rearranged word, e.g. tree -> eert

Examples

Input
tree
Output
eert
Input
abc
Output
abc
Input
mississippi
Output
iiiissssppm

One more test checks other inputs when you press Check.

Stuck? The idea behind sorting algorithms

Bubble sort swaps neighbours that are in the wrong order, pass after pass. Insertion sort takes each item in turn and slides it back into place among those before it. Merge sort splits the list, sorts each half and merges them.

These exercises ask for the steps, not just the result: write the algorithm yourself rather than calling sorted().

a = [5, 1, 4, 2]
for end in range(len(a) - 1, 0, -1):
    for i in range(end):
        if a[i] > a[i + 1]:
            a[i], a[i + 1] = a[i + 1], a[i]
print(a)

Watch for: Off-by-one: comparing a[i] with a[i + 1] means i must stop one before the end.

All the sorting algorithms exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More sorting algorithms exercises