Menu
Coddy logo textTech

Anagram Groups

Part of the Logic & Flow section of Coddy's Swift journey — lesson 54 of 56.

challenge icon

Challenge

Medium

Two words are anagrams if their sorted letters match: listen and silent both sort to eilnst.

Read a single line of input: a comma-separated list of words (lower-case, no whitespace inside words).

Group the words by their sorted-letter signature. Print, in this order:

  1. One line per group with two or more words, in the format <signature>: <word1>,<word2>,.... Within a group, keep the words in input order. Sort the groups alphabetically by signature.
  2. Total groups: <n> (count of groups with two or more words).

For input listen,silent,abc,enlist,cab,xyz, the output is:

abc: abc,cab
eilnst: listen,silent,enlist
Total groups: 2

Try it yourself

let words = readLine()!.components(separatedBy: ",")

// TODO: build [signature: [word]]; print sorted groups with size >= 2;
// then print 'Total groups: <n>'

All lessons in Logic & Flow