The sort | uniq -c | sort -rn idiom is one of the most useful three-command pipelines
in existence. Bioinformaticians use it constantly: counting reads per chromosome from a SAM file,
tallying variant types in a VCF, summarising species in a metagenomic classification. It also
demonstrates why pipes matter — each tool does one thing, and their composition does something none of
them could alone.
Statement
A list of values arrives on standard input, one per line.
Count how many times each distinct value appears, and print the results sorted by count descending. Where
counts tie, sort by value ascending lexicographically.
Print each result as <count> <value> separated by a single space, one per line.
Input — read from standard input
| Variable | Type | Description |
|---|---|---|
values
line 1..n
|
str |
One value per line
1 <= lines <= 5000, values contain no whitespace
|
These variables are already read for you in the starter code on the right.
Output
str one line per distinct value as count then value, sorted by count descending then value ascending
Sample Cases
chr1
chr2
chr1
chr3
chr1
chr2
3 chr1
2 chr2
1 chr3
SNP
INDEL
SNP
2 SNP
1 INDEL
Submit also runs your code against 3 hidden test cases. Hidden inputs are never shown — if one fails you'll get its number and a description of the mismatch, not the data.
Constraints
- Values contain no spaces or tabs
- Output separator is a single space, not a tab or padded columns
- Ties in count are broken by value ascending, which makes output deterministic
- Blank lines in the input are ignored
Further Reading
uniq -crequires its input to be sorted first, or repeated values in different places are counted
separately.uniq -cpads its counts with leading spaces —awk '{print $1, $2}'normalises the spacing.- Sorting by two keys at once:
sort -k1,1nr -k2,2gives numeric descending on the count and
lexicographic ascending on the value.
Judged against GNU Bash 5.1.0.