Interview Questions - Software Developer

Find most common occurrence "element" in an array:

========================================================================

For Example: [6, 7, 1, 4, 6]  -> 6

static void CommonOccurence(int[] numbers){
        var counts = new Dictionary<int, int>();
         foreach(int n in numbers){
             int count;
             counts.TryGetValue(n, out count);
             count++;
             counts[n] = count;
        }
       
         int mostCommonNum = 0, occurences = 0;
         foreach(var pair in counts){
             if(pair.value > occurences){
                  pair.value = occurences;
                  mostCommonNum = pair.Key;
            }
        }
       Console.WriteLine("Most common number is : {0} and the occurences is : {1}",              mostCommonNum, occurences);
    }

 


Comments