Implement the groupAnagramCount method that counts how many anagram groups are formed from the words.

The input contains an array of strings words and its length size. Your task is to group words that are anagrams of each other and return the number of groups formed.

For example, [eat,tea,tan,ate,nat,bat] forms three groups: [eat,tea,ate], [tan,nat], and [bat], so the answer is 3.

Example 1

Input
words (string[]) = [eat,tea,tan,ate,nat,bat]
size (int) = 6
Returns (int) 3

Example 2

Input
words (string[]) = [a]
size (int) = 1
Returns (int) 1

Example 3

Input
words (string[]) = [abc,bca,cab,foo]
size (int) = 4
Returns (int) 2

All anagrams have the same characters after sorting their letters.

For each word, sort its characters to create a common key. Store that key in a set or map. Words with the same sorted key belong to the same anagram group.

After processing all words, the number of unique keys is the number of anagram groups.

Pseudocode:

function groupAnagramCount(words, size):
    groups = empty set
    for i from 0 to size - 1:
        key = characters of words[i] sorted in ascending order
        add key to groups
    return size of groups
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.