A desert caravan logs a cargo tag at every checkpoint along its route. Each tag is a lowercase word describing the bundle carried at that stop. The quartermaster patrols the manifest looking for two neighboring checkpoints whose tags use exactly the same letters in some order (an anagram of one another); whenever such a pair is found, the later entry is struck out as a redundant echo of the one right before it. Because striking an entry can bring two tags that were not originally adjacent together, the quartermaster repeats this check — scanning for any adjacent anagram pair and striking the second one — for as long as any such pair remains anywhere in the manifest. Once no two neighboring tags are anagrams of each other, report the manifest that is left.
Print the final manifest as space-separated tags, in their remaining relative order, on a single line.
Example 1
Input
5 abba baba bbaa cd cd
Expected
abba cd
Explanation
abba and baba use the same letters, so baba is struck; the manifest becomes [abba, bbaa, cd, cd]. abba and bbaa are also anagrams, so bbaa is struck, leaving [abba, cd, cd]. Now the two cd entries are (trivially) anagrams of each other, so the second cd is struck, leaving [abba, cd]. No adjacent pair remains an anagram pair, so the output is "abba cd".
Example 2
Input
4 face ecaf cash dog
Expected
face cash dog
Explanation
face and ecaf share the letters a, c, e, f, so ecaf is struck, leaving [face, cash, dog]. cash and dog share no letters and face/cash also do not match, so no further strikes happen. The output is "face cash dog".
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 →