The task was to check for pairs of anagrams in a string list.
- I first sorted all the words. and looped over the letters.
- The interview continues with a follow-up, to do the same with limited memory. I tried to implement a Hash function.
The dictionary return value is only for my convince in order to see all the pairs. I could just print it into the console instead.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class ReverseString
{
public ReverseString()
{
List<string> anagarms = new List<string>();
anagarms.Add("Gilad");
anagarms.Add("dilaG");
anagarms.Add("bat");
anagarms.Add("but");
anagarms.Add("utb");
pairs = PairAnagrams(anagarms);
pairs = PairAnagramsHash(anagarms);
}
Dictionary<string, string> PairAnagrams(List<string> wordsList)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach(var item in wordsList)
{
if (dictionary.ContainsValue(item))
{
continue;
}
foreach(var item2 in wordsList)
{
if(item.Length != item2.Length || item.Equals(item2))
{
continue;
}
var sortedWord1 = item.ToArray();
Array.Sort(sortedWord1);
var sortedWord2 = item2.ToArray();
Array.Sort<char>(sortedWord2);
int i;
for (i = 0; i < sortedWord2.Length; i++)
{
if (sortedWord2[i] != sortedWord1[i])
{
break;
}
}
if(i == sortedWord1.Length)
{
dictionary.Add(item, item2);
}
}
}
return dictionary;
}
Dictionary<string, string> PairAnagramsHash(List<string> wordList)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (var item in wordList)
{
foreach (var item2 in wordList)
{
if (item.Equals(item2) || dictionary.ContainsKey(item2))
{
continue;
}
if (HashFunction(item) == HashFunction(item2))
{
dictionary.Add(item, item2);
}
}
}
return dictionary;
}
public int HashFunction(string word)
{
int result = 0;
var charArray = word.ToArray();
for (int i = 0; i < word.Length; i++)
{
result += charArray[i] * 37;
}
return result;
}
}
}