Skip to content

Instantly share code, notes, and snippets.

@iAmWillShepherd
Created April 27, 2016 19:24
Show Gist options
  • Save iAmWillShepherd/772f5fcbca2f5ed274d5d634b8825c78 to your computer and use it in GitHub Desktop.
Save iAmWillShepherd/772f5fcbca2f5ed274d5d634b8825c78 to your computer and use it in GitHub Desktop.
Solution to Missing Numbers problem on HackerRank
void Main()
{
var size_a = int.Parse(Console.ReadLine());
var list_a = Console.ReadLine()
.Split(' ')
.Take(size_a)
.Select(x => int.Parse(x))
.ToList();
var size_b = int.Parse(Console.ReadLine());
var list_b = Console.ReadLine()
.Split(' ')
.Take(size_b)
.Select(x => int.Parse(x))
.ToList();
var hashMapA = new Dictionary<int, int>();
var hashMapB = new Dictionary<int, int>();
foreach (var i in list_a)
{
hashMapA.InsertOrUpdate(i);
}
foreach (var i in list_b)
{
hashMapB.InsertOrUpdate(i);
}
var missingValues = new HashSet<int>();
foreach (var key_a in hashMapA.Keys)
{
if (!hashMapB.ContainsKey(key_a))
{
missingValues.Add(key_a);
}
else
{
var count_a = hashMapA[key_a];
var count_b = hashMapB[key_a];
if (count_a - count_b != 0)
{
missingValues.Add(key_a);
}
}
}
foreach (var key_b in hashMapB.Keys)
{
if (!hashMapA.ContainsKey(key_b))
{
missingValues.Add(key_b);
}
else
{
var count_a = hashMapA[key_b];
var count_b = hashMapB[key_b];
if (count_a - count_b != 0)
{
missingValues.Add(key_b);
}
}
}
Console.WriteLine(missingValues.OrderBy(_ => _).Aggregate(string.Empty, (acc, x) => acc + " " + x).TrimStart());
}
public static class DictionaryExtension
{
public static void InsertOrUpdate(this Dictionary<int, int> hashMap, int key)
{
int val;
if (hashMap.ContainsKey(key))
{
hashMap[key]++;
}
else
{
hashMap.Add(key, 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment