using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.IO; using System.Xml; using System.Text.RegularExpressions; public interface ICodeRush { int? FindLeastFrequentNumber(IList list); } public class Solution : ICodeRush { public int? FindLeastFrequentNumber(IList list) { // return null for null or empty lists if (list == null || list.Count == 0) { return null; } Dictionary found = new Dictionary(list.Count / 4); for (int index = 0; index < list.Count; ++index) { // Two hashes per update - could be worse I guess int current = list[index]; int count; if (found.TryGetValue(current, out count)) { ++count; found[current] = count; } else { found.Add(current, 1); } } int smallest = 0; int smallestVal = int.MaxValue; // Pay the penalty once to make this a list; faster to iterate after var data = found.ToList(); for (int index = 0; index < data.Count; ++index) { var item = data[index]; if (item.Value < smallestVal) { // If we ever reach a 1, nothing will be lower, so just return this key now if (item.Value == 1) { return item.Key; } // If this is smaller than the least frequent so far, store the key and value else { smallest = item.Key; smallestVal = item.Value; } } } return smallest; } }