A glossary must be sorted according to a custom alphabet: a given permutation of the 26 lowercase English letters that defines the collation order (the first letter of the permutation is treated as smallest). Sort the given words in ascending order under this custom alphabet, using the usual lexicographic rule (compare letter by letter using the custom order; if one word is a prefix of another, the shorter word comes first). Duplicate words are allowed.
Line 1: a 26-character string, a permutation of a-z giving the custom order.
Line 2: an integer n.
The next n tokens (each on its own line) are the words (lowercase letters only).
The n words, one per line, sorted ascending under the custom alphabet.
Example 1
Input
bacdefghijklmnopqrstuvwxyz 3 ab ba aa
Expected
ba ab aa
Explanation
Here b ranks before a. Comparing: ba (b,a) < ab (a,b) < aa (a,a). So the order is ba, ab, aa.
Example 2
Input
abcdefghijklmnopqrstuvwxyz 3 cat car cab
Expected
cab car cat
Explanation
The custom order is the normal alphabet, so cab, car, cat sort in ordinary lexicographic order.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →