Search⌘ K
AI Features

Challenge: Group Anagrams

Explore how to identify and group anagrams within a list of strings using sorting and searching techniques. Understand the impact of spaces on anagram detection and practice designing a clear algorithm to solve this coding challenge effectively.

Problem statement

Given a list of strings that contain anagrams, write a function to print pairs of those anagrams.

Input

A list of strings. Remember that spaces count as characters. So, " abc" and "cab" are technically not anagrams since " abc" has spaces, which "cab" does not.

Output

A list of lists where all pairs of anagrams are grouped together.

Sample input

input = {
    "tom marvolo riddle ",
    "abc",
    "def",
    "cab",
    "fed",
    "brag",
    "clint eastwood ",
    "i am lord voldemort",
    "elvis",
    "grab",
    "old west action",
    "lives"
};

Sample output

result = {
    {"abc", "cab"},
    {"clint eastwood ", "old west action"},
    {"def", "fed"},
    {"elvis", "lives"}
};

Note: The order of the anagrams doesn’t matter!

Coding exercise

First, take a close look at this problem, design a step-by-step algorithm, and then jump on to implementation. This problem is designed for your practice, so try to solve it on your own first. If you get stuck, you can always refer to the solution provided in the next section.

C# 9.0
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
/// <summary>
/// Method to find anagram pairs.
/// </summary>
/// <param name="arr">An array of strings.</param>
/// <returns>Group of anagrams.</returns>
public static List<List<string>> Anagrams(string[] arr)
{
return new List<List<string>>();
}
}